LintCode 230 [Animal Shelter]

原题

在一个宠物避难所里,仅有狗和猫两种动物可供领养,且领养时严格执行“先进先出”的规则。如果有人想要从避难所领养动物,他只有两种选择:要么选择领养所有动物中最资深的一只(根据到达避难所的时间,越早到的越资深),要么选择领养猫或狗(同样,也只能领养最资深的一只)。也就是说,领养者不能随意选择某一指定动物。请建立一个数据结构,使得它可以运行以上规则,并可实 enqueue, dequeueAny, dequeueDog, 和 dequeueCat 操作。
建议使用 LinkedList 作为数据结构实现。

样例

int DOG = 1
int CAT = 2

enqueue("james", DOG);
enqueue("tom", DOG);
enqueue("mimi", CAT);
dequeueAny();  # should return "james"
dequeueCat();  # should return "mimi"
dequeueDog();  # should return "tom"

解题思路

  • 使用两个数组分别记录加入的猫和狗,用0和1表示
  • 存储时,在python中可以使用set来同时记录名字和先后顺序(使用数字记录age),初始tot = 0,之后每次tot += 1,在dequeueAny的时候只需要比较Dog[0]和Cat[0]的tot,值越小表明age越大,pop谁

完整代码

class AnimalShelter(object):

    def __init__(self):
        # do some intialize if necessary
        self.cats = []
        self.dogs = []
        self.tot = 0

    """
    @param {string} name
    @param {int} type, 1 if Animal is dog or 0
    @return nothing
    """
    def enqueue(self, name, type):
        # Write yout code here
        self.tot += 1
        if type == 1:
            self.dogs.append((name, self.tot))
        else:
            self.cats.append((name, self.tot))

    # return a string
    def dequeueAny(self):
        # Write your code here
        if len(self.dogs) == 0:
            return self.dequeueCat()
        elif len(self.cats) == 0:
            return self.dequeueDog()
        else:
            if self.dogs[0][1] < self.cats[0][1]:
                return self.dequeueDog()
            else:
                return self.dequeueCat()

    # return a string
    def dequeueDog(self):
        # Write your code here
        name = self.dogs[0][0]
        del self.dogs[0]
        return name

    # return a string
    def dequeueCat(self):
        # Write your code here
        name = self.cats[0][0]
        del self.cats[0]
        return name

你可能感兴趣的:(LintCode 230 [Animal Shelter])