一起用代码吸猫!本文正在参与【喵星人征文活动】。
题目改编于:LeetCode-面试题 03.06. 动物收容所
题目
一起用代码吸猫之喵咪收容所。有家喵咪收容所为了让每一只猫咪都能过上幸福决定,严格遵守“先进先出”的原则。在收养该收容所的猫咪时,为了能更好的管理猫咪以及保证喵咪“身体完整”收容所决定根据喵咪性别分开管理。收养人在领养过程中只能收养所有猫咪中最先进入收容所的。换言之,收养人不能自由挑选想收养的对象。请创建适用于这个系统的数据结构,实现各种操作方法,enqueue
、dequeueAny
、dequeueMaleCat
和dequeueFemaleCat
。
enqueue
方法有一个animal
参数,animal[0]
代表猫咪编号,animal[1]
代表猫咪性别,其中 0
代表公猫,1
代表母猫。
dequeue*
方法返回一个列表[猫咪编号, ,猫咪性别]
,若没有可以收养的动物,则返回[-1,-1]
。
分析
- 根据题目来看此猫咪收容所遵守
“先进先出”
的原则,适合用队列
来解决问题。 - 根据性别分为两个队列
- 通过
push
函数来往队列内添加元素,实现收容喵咪的动作 - 通过
shift
函数删除首个数组元素,实现收养,喵咪的动作
步骤
定义
CatShelf
类并定义queueMaleCat
、queueFemaleCat
,分别管理公猫、母猫。
var CatShelf = function() {
this.queueMaleCat = [];
this.queueFemaleCat = [];
};
通过原型链
prototype
实现enqueue
收留喵咪,通过判断猫咪性别分别进行入队操作
AnimalShelf.prototype.enqueue = function(animal) {
if(animal[1] == 0){
this.queueMaleCat.push(animal[0]);
} else {
this.queueFemaleCat.push(animal[0]);
}
}
通过原型链
prototype
实现dequeueAny
收留喵咪。
情况一俩个队列里都没有猫咪,直接返回[-1,-1]
情况二公猫队列里没有,母猫里有,返回母猫队列第一只喵咪 情况三母猫队列里没有,公猫里有,返回公猫队列第一只喵咪
AnimalShelf.prototype.dequeueAny = function() {
if(this.queueMaleCat.length == 0 && this.queueFemaleCat.length == 0){
return [-1,-1];
}
if(this.queueMaleCat.length == 0){
return [this.queueMaleCat.shift(), 0];
}
if(this.queueFemaleCat.length == 0){
return [this.queueFemaleCat.shift(), 1];
}
return this.queueMaleCat[0] < this.queueFemaleCat[0] ?
[this.queueMaleCat.shift(), 0] :
[this.queueFemaleCat.shift(), 1];
};
dequeueMaleCat
收养公猫
AnimalShelf.prototype.dequeueMaleCat = function() {
if(this.queueMaleCat.length == 0) return[-1, -1];
return [this.queueMaleCat.shift(), 0];
};
实现
dequeueFemaleCat
收养母猫
AnimalShelf.prototype.dequeueFemaleCat = function() {
if(this.queueFemaleCat.length == 0) return [-1, -1];
return [this.queueFemaleCat.shift(), 1];
};
完整代码
var CatShelf = function() {
this.queueMaleCat = [];
this.queueFemaleCat = [];
};
/**
* @param {number[]} animal
* @return {void}
*/
AnimalShelf.prototype.enqueue = function(animal) {
if(animal[1] == 0){
this.queueMaleCat.push(animal[0]);
} else {
this.queueFemaleCat.push(animal[0]);
}
}
/**
* @return {number[]}
*/
AnimalShelf.prototype.dequeueAny = function() {
if(this.queueMaleCat.length == 0 && this.queueFemaleCat.length == 0){
return [-1,-1];
}
if(this.queueMaleCat.length == 0){
return [this.queueMaleCat.pop(), 1];
}
if(this.queueFemaleCat.length == 0){
return [this.queueFemaleCat.shift(), 0];
}
return this.queueMaleCat[0] < this.queueFemaleCat[0] ?
[this.queueMaleCat.shift(), 0] :
[this.queueFemaleCat.shift(), 1];
};
/**
* @return {number[]}
*/
AnimalShelf.prototype.dequeueMaleCat = function() {
if(this.queueMaleCat.length == 0) return[-1, -1];
return [this.queueMaleCat.shift(), 1];
};
/**
* @return {number[]}
*/
AnimalShelf.prototype.dequeueFemaleCat = function() {
if(this.queueFemaleCat.length == 0) return [-1, -1];
return [this.queueFemaleCat.shift(), 0];
};
最后还望广大养猫人士既然决定要养,请不要抛弃。铲屎官们对你家猫咪好些!