LeetCode 算法:动物收容所

453 阅读3分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第 10 天,点击查看活动详情

动物收容所

原题地址

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

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. 使用数组来表示这个动物收容所,按照题目描述,可以得知是一个二维数组,其中每一项的 [0] 表示动物编号, [1] 表示动物种类,只有两个值 0 和 1
  2. enqueue 是相当于动物进入收容所,将对应的 animal 使用数组的 push 方法放入 this.animal
  3. dequeueAny 领养任意一个动物,因为遵循先进先出的原则,因此越往前的动物年龄越长,因此领养任意一个动物使用 this.animal.shift() 即可,此方法删除数组的第一个元素并返回;需要判断边界值,若动物收容所没有动物,即 this.animal.length === 0 时,没法收养,返回 [-1, -1]
  4. dequeueDogdequeueCat 是类似的处理方法,首先处理边界值,将 this.animal 中的 猫和狗 过滤出来存储到 animal 中,若 animal.length === 0,没法收养,返回 [-1, -1]。然后再寻找原数组中,猫和狗出现的第一个下标,使用 splice 方法删除对应位置上的元素并返回即可,因为是二维数组,因此需要取第一个元素返回。

AC 代码

方法一

var AnimalShelf = function() {
    this.animal = []
};

/** 
 * @param {number[]} animal
 * @return {void}
 */
AnimalShelf.prototype.enqueue = function(animal) {
    this.animal.push(animal)
};

/**
 * @return {number[]}
 */
AnimalShelf.prototype.dequeueAny = function() {
    if(!this.animal.length) return [-1, -1]
    return this.animal.shift()
};

/**
 * @return {number[]}
 */
AnimalShelf.prototype.dequeueDog = function() {
    const animal = this.animal.filter(item => item[1] === 1)
    if(!animal.length) return [-1, -1]
    const index = this.animal.findIndex(item => item[1] === 1)
    return this.animal.splice(index, 1)[0]
};

/**
 * @return {number[]}
 */
AnimalShelf.prototype.dequeueCat = function() {
    const animal = this.animal.filter(item => item[1] === 0)
    if(!animal.length) return [-1, -1]
    const index = this.animal.findIndex(item => item[1] === 0)
    return this.animal.splice(index, 1)[0]
};

/**
 * Your AnimalShelf object will be instantiated and called as such:
 * var obj = new AnimalShelf()
 * obj.enqueue(animal)
 * var param_2 = obj.dequeueAny()
 * var param_3 = obj.dequeueDog()
 * var param_4 = obj.dequeueCat()
 */

结果:

  • 执行结果: 通过
  • 执行用时:176 ms, 在所有 JavaScript 提交中击败了74.74%的用户
  • 内存消耗:58.1 MB, 在所有 JavaScript 提交中击败了33.69%的用户
  • 通过测试用例:31 / 31

END