题目难度: 简单

原题链接

今天继续更新程序员面试金典系列, 大家在公众号 算法精选 里回复 面试金典 就能看到该系列当前连载的所有文章了, 记得关注哦~

题目描述

动物收容所。有家动物收容所只收容狗与猫,且严格遵守“先进先出”的原则。在收养该收容所的动物时,收养人只能收养所有动物中“最老”(由其进入收容所的时间长短而定)的动物,或者可以挑选猫或狗(同时必须收养此类动物中“最老”的)。换言之,收养人不能自由挑选想收养的对象。请创建适用于这个系统的数据结构,实现各种操作方法,比如 enqueue、dequeueAny、dequeueDog 和 dequeueCat。允许使用 Java 内置的 LinkedList 数据结构。

enqueue 方法有一个 animal 参数,animal[0]代表动物编号,animal[1]代表动物种类,其中 0 代表猫,1 代表狗。

dequeue 方法返回一个列表[动物编号, 动物种类],若没有可以收养的动物,则返回[-1,-1]。

示例 1:

  • 输入:
    • ["AnimalShelf", "enqueue", "enqueue", "dequeueCat", "dequeueDog", "dequeueAny"]
    • [[], [[0, 0]], [[1, 0]], [], [], []]
  • 输出:
    • [null,null,null,[0,0],[-1,-1],[1,0]]

示例 2:

  • 输入:
    • ["AnimalShelf", "enqueue", "enqueue", "enqueue", "dequeueDog", "dequeueCat", "dequeueAny"]
    • [[], [[0, 0]], [[1, 0]], [[2, 1]], [], [], []]
  • 输出:
    • [null,null,null,null,[2,1],[0,0],[1,0]]

说明:

  • 收纳所的最大容量为 20000

题目思考

  1. 需要哪些数据结构?

解决方案

思路

  • 由于需要可以单独挑选猫或狗, 所以需要两个双端队列来存对应的编号
  • 另外又有需求来挑选猫或狗中最老的, 所以我们还要额外维护动物加入队列的时间, 也要将这一信息和编号一起入队, 入队后再将时间+1
  • 这样出队最老的动物时, 只需要比较两个队列开头的时间, 然后选择更老的那只动物即可

复杂度

  • 时间复杂度 O(1): 显然每种操作都只需要常数时间
  • 空间复杂度 O(N): 使用了两个双端队列存 N 个元素

代码

import collections


class AnimalShelf:
    def __init__(self):
        # 两个双端队列+当前入队时间
        self.cats = collections.deque()
        self.dogs = collections.deque()
        self.age = 0

    def enqueue(self, animal: List[int]) -> None:
        id, t = animal
        # 根据动物种类, 加入到相应队列中
        if t == 0:
            self.cats.append((id, self.age))
        else:
            self.dogs.append((id, self.age))
        # 注意更新时间
        self.age += 1

    def dequeueAny(self) -> List[int]:
        if not self.dogs and not self.cats:
            # 两个队列都没有动物
            return [-1, -1]
        if not self.dogs or self.cats and self.cats[0][1] < self.dogs[0][1]:
            # 没有狗, 或者猫更老, 将最老的猫出队
            return [self.cats.popleft()[0], 0]
        else:
            # 此时说明没有猫或者狗更老, 将最老的狗出队
            return [self.dogs.popleft()[0], 1]

    def dequeueDog(self) -> List[int]:
        if not self.dogs:
            # 没有狗了
            return [-1, -1]
        # 将最老的狗出队
        return [self.dogs.popleft()[0], 1]

    def dequeueCat(self) -> List[int]:
        if not self.cats:
            # 没有猫了
            return [-1, -1]
        # 将最老的猫出队
        return [self.cats.popleft()[0], 0]

大家可以在下面这些地方找到我~😊

我的知乎专栏

我的头条号

我的 CSDN

我的 Leetcode

我的牛客网博客

我的公众号: 算法精选, 欢迎大家扫码关注~😊

算法精选 - 微信扫一扫关注我