美文网首页
LeetCode习题:动物收容所

LeetCode习题:动物收容所

作者: 华子的学习之路 | 来源:发表于2021-04-24 23:28 被阅读0次

题目描述:动物收容所。有家动物收容所只收容狗与猫,且严格遵守“先进先出”的原则。在收养该收容所的动物时,收养人只能收养所有动物中“最老”(由其进入收容所的时间长短而定)的动物,或者可以挑选猫或狗(同时必须收养此类动物中“最老”的)。换言之,收养人不能自由挑选想收养的对象。请创建适用于这个系统的数据结构,实现各种操作方法,比如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

解题思路:充分理解题目描述

解题语言: Swift

class AnimalShelf {

    private var queue = [[Int]]()

    init() {
    }
    
    func enqueue(_ animal: [Int]) {
        queue.append(animal)
    }
    
    func dequeueAny() -> [Int] {
        if queue.isEmpty {
            return [-1, -1]
        }
        let animal = queue.removeFirst()
        return animal
    }
    
    func dequeueDog() -> [Int] {
        return findType(1)
    }
    
    func dequeueCat() -> [Int] {
        return findType(0)
    }

    private func findType(_ animationType: Int) -> [Int] {
        if queue.isEmpty {
            return [-1, -1]
        }
        var index: Int?
        for (i, item) in queue.enumerated() {
            if item.last == animationType {
                index = i
                break
            }
        }
        if index != nil {
            let animal = queue.remove(at: index!)
            return animal;
        }
        return [-1, -1]
    }
}

复杂度分析:

时间复杂度:O(n),其中n为动物收容所动物总数
空间复杂度: O(n), 其中n为动物收容所动物总数
题目来源:LeetCode

相关文章

  • LeetCode习题:动物收容所

    题目描述:动物收容所。有家动物收容所只收容狗与猫,且严格遵守“先进先出”的原则。在收养该收容所的动物时,收养人只能...

  • 不积跬步,无以至千里

    02、面试题 03.06. 动物收容所 https://leetcode-cn.com/problems/anim...

  • 2021-04-17算法打卡

    1、猫狗收容所动物收容所。有家动物收容所只收容狗与猫,且严格遵守“先进先出”的原则。在收养该收容所的动物时,收养人...

  • 面试题 03.06. 动物收容所

    题意:动物收容所。有家动物收容所只收容狗与猫,且严格遵守“先进先出”的原则。在收养该收容所的动物时,收养人只能收养...

  • Python算法学习——个人日记系列(1)

    以Leetcode的练习题作为练习,来从零基础练习算法。 https://leetcode.com/problem...

  • 国外VI品牌形象作品集锦

    Battersea动物收容所视觉形象设计 ▼ HIGHER-GROUND品牌形象设计 ▼Lucid Motors新...

  • 《天之义》第二十四章:方法

    到了晚上,布莱恩、菲丽丝和收容所里的其他动物都睡了,只剩下Aimiliya和Bobiy没睡,他们要向其他动物打听菲...

  • leetcode习题762

    tags: Bit Manipulation categories: leetcode 题目: 给定两个整数 L...

  • leetcode习题练习

    反转整数 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。 题目链接https://lee...

  • “我还一直在原地等你……”

    写给主人的一封信 今天我不幸离开了 你对我感到厌倦了,所以你把我送去了收容所。收容所的动物已经太多了,而我抽到了不...

网友评论

      本文标题:LeetCode习题:动物收容所

      本文链接:https://www.haomeiwen.com/subject/lisrrltx.html