有家动物收容所只收留猫和狗,但有特殊的收养规则,收养人有两种收养方式,第一种为直接收养所有动物中最早进,入收容所的,第二种为选择收养的动物类型(猫或狗),并收养该种动物中最早进,入收容所的。
给定一个操作序列int口[2] ope代表所有事件。
若第一个元素为1,则代表有动物进入收容所,第二个元素为动物的编号,正数代表狗,负数代表猫;
若第一个元素为2,则代表有人收养动物,第二个元素若为0,则采取第一种收养方式(最早),若为1,则指定收养狗,若为-1则指定收养猫。
请按顺序返回收养的序列。若出现不合法的操作,即没有可以符合领养要求的动物,则将这次领养操作忽略。
测试样例:
输入:
[[1,1],[1, -1],[2,0],[2,-1]]
输出:
[1,-1]
思路:
可以用两个队列catQueue和dogQueue用来进行猫和狗的入队操作和出队操作,如果想领养猫就只从catQueue出队,想养狗就是dogQueue出队,如果两个都可以就从两个队列中选择更早进入收容所的动物出队。
代码实现:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
private static class Animal {
//动物的类型(猫或狗)
int type;
//动物进入收容所的时间(猫和狗共享的静态变量)
static int timeline;
//猫或狗独有的代表进入时间点的变量
int time;
//构造函数
public Animal(int typeNumber) {
//初始化动物类型
this.type = typeNumber;
//按时间线递增的顺序给猫或狗的时间点赋值
this.time = timeline++;
}
}
public ArrayList<Integer> solve(int[][] ope) {
ArrayList<Integer> res = new ArrayList<>();
//猫队列
Queue<Animal> catQueue = new LinkedList<>();
//狗队列
Queue<Animal> dogQueue = new LinkedList<>();
for (int[] animal : ope) {
if (animal[0] == 1) {
if (animal[1] > 0) {
dogQueue.add(new Animal(animal[1]));
} else if (animal[1] < 0) {
catQueue.add(new Animal(animal[1]));
}
} else if (animal[0] == 2) {
if (animal[1] == 1 && !dogQueue.isEmpty()) {
res.add(dogQueue.poll().type);
} else if (animal[1] == -1 && !catQueue.isEmpty()) {
res.add(catQueue.poll().type);
} else if (animal[1] == 0) {
if (!catQueue.isEmpty() && dogQueue.isEmpty() || catQueue.peek().time < dogQueue.peek().time) {
res.add(catQueue.poll().type);
} else if (!dogQueue.isEmpty() && catQueue.isEmpty() || dogQueue.peek().time < catQueue.peek().time) {
res.add(dogQueue.poll().type);
}
}
}
}
return res;
}
//测试方法
public static void main(String[] args) {
int[][] dada = {{1, 1}, {1, -1}, {2, 0}, {2, -1}};
System.out.println(new Main().solve(dada).toString().trim());
}
}