题目难度: 简单
原题链接[1]
题目描述今天继续更新程序员面试金典系列, 大家在公众号 算法精选 里回复 面试金典 就能看到该系列当前连载的所有文章了, 记得关注哦~
动物收容所。有家动物收容所只收容狗与猫,且严格遵守“先进先出”的原则。在收养该收容所的动物时,收养人只能收养所有动物中“最老”(由其进入收容所的时间长短而定)的动物,或者可以挑选猫或狗(同时必须收养此类动物中“最老”的)。换言之,收养人不能自由挑选想收养的对象。请创建适用于这个系统的数据结构,实现各种操作方法,比如 enqueue、dequeueAny、dequeueDog 和 dequeueCat。允许使用 Java 内置的 LinkedList 数据结构。
enqueue 方法有一个 animal 参数,animal[0]代表动物编号,animal[1]代表动物种类,其中 0 代表猫,1 代表狗。
dequeue 方法返回一个列表[动物编号, 动物种类],若没有可以收养的动物,则返回[-1,-1]。
示例 1:importcollections
classAnimalShelf:
def__init__(self):
#两个双端队列 当前入队时间
self.cats=collections.deque()
self.dogs=collections.deque()
self.age=0
defenqueue(self,animal:List[int])->None:
id,t=animal
#根据动物种类,加入到相应队列中
ift==0:
self.cats.append((id,self.age))
else:
self.dogs.append((id,self.age))
#注意更新时间
self.age =1
defdequeueAny(self)->List[int]:
ifnotself.dogsandnotself.cats:
#两个队列都没有动物
return[-1,-1]
ifnotself.dogsorself.catsandself.cats[0][1]<self.dogs[0][1]:
#没有狗,或者猫更老,将最老的猫出队
return[self.cats.popleft()[0],0]
else:
#此时说明没有猫或者狗更老,将最老的狗出队
return[self.dogs.popleft()[0],1]
defdequeueDog(self)->List[int]:
ifnotself.dogs:
#没有狗了
return[-1,-1]
#将最老的狗出队
return[self.dogs.popleft()[0],1]
defdequeueCat(self)->List[int]:
ifnotself.cats:
#没有猫了
return[-1,-1]
#将最老的猫出队
return[self.cats.popleft()[0],0]
参考资料
[1]
原题链接: https://leetcode-cn.com/problems/animal-shelter-lcci/
Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved