题目链接
动物收容所
题目描述
注意点
- 若没有可以收养的动物,则返回[-1,-1]
 - 收纳所的最大容量为20000
 - 编号随着收养动物的增加自增
 
解答思路
- 利用队列先进先出的特点将猫和狗分别存进两个队列中,关键是dequeueAny这个方法中如果此时猫和狗的队列中都有元素则需要根据其编号选择相应的猫或狗
 
代码
class AnimalShelf {
    Deque<int[]> dogDq;
    Deque<int[]> catDq;
    public AnimalShelf() {
        dogDq = new ArrayDeque<>();
        catDq = new ArrayDeque<>();
    }
    
    public void enqueue(int[] animal) {
        if (animal[1] == 0) {
            catDq.offerLast(animal);
        }
        if (animal[1] == 1) {
            dogDq.offerLast(animal);
        }
    }
    
    public int[] dequeueAny() {
        if (dogDq.isEmpty() && catDq.isEmpty()) {
            return new int[]{-1, -1};
        }
        if (dogDq.isEmpty()) {
            return catDq.pollFirst();
        }
        if (catDq.isEmpty()) {
            return dogDq.pollFirst();
        }
        return catDq.peek()[0] > dogDq.peek()[0] ? dogDq.pollFirst() : catDq.pollFirst();
    }
    
    public int[] dequeueDog() {
        if (dogDq.isEmpty()) {
            return new int[]{-1, -1};
        }
        return dogDq.pollFirst();
    }
    
    public int[] dequeueCat() {
        if (catDq.isEmpty()) {
            return new int[]{-1, -1};
        }
        return catDq.pollFirst();
    }
}
 
关键点
- 编号随着收养动物的增加自增
 - 注意边界问题
 




















