[java] Queue 猫狗收容所
寒光博客 • 2019 年 10 月 26 日
CatDogAsylum
cc150 模拟
有家动物收容所只收留猫和狗,但有特殊的收养规则,收养人有两种收养方式,
第一种为直接收养所有动物中最早进入收容所的,
第二种为选择收养的动物类型(猫或狗),并收养该种动物中最早进入收容所的。
给定一个操作序列int[][2] ope(C++中为vector)代表所有事件。
若第一个元素为1,则代表有动物进入收容所,第二个元素为动物的编号,正数代表狗,负数代表猫;
若第一个元素为2,则代表有人收养动物,第二个元素若为0,则采取第一种收养方式(最早),
若为1,则指定收养狗,若为-1则指定收养猫。
请按顺序返回收养的序列。若出现不合法的操作,即没有可以符合领养要求的动物,则将这次领养操作忽略。
测试样例:
[[1,1],[1,-1],[2,0],[2,-1]]
返回:
[1,-1]
代码
package _09_Linear.Stack_QueuePractice;
import org.junit.Test;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class CatDogAsylum {
@Test
public void test() {
int[][] data = {{1, 1}, {1, -1}, {1, 0}, {1, -5}, {2, 0}, {2, -1}, {2, 0}};
ArrayList ans=asylum(data);
System.out.println(ans.toString().trim());
}
private static class Animal {
int type;//编号
int time;//加入时间
static int timeLine = 0;//全局变量 先后顺序 特征值
Animal(int type) {
this.type = type;
time = timeLine++;
}
}
public ArrayList asylum(int[][] ope) {
ArrayList asylum = new ArrayList<>();
Queue cats = new LinkedList<>();
Queue dogs = new LinkedList<>();
for (int[] inAndOut : ope) {
int op = inAndOut[0];
int typeNumber = inAndOut[1];
if (op == 1) {//有动物进入
if (typeNumber > 0) {//dog
dogs.add(new Animal(typeNumber));
} else if (typeNumber < 0) {//cat
cats.add(new Animal(typeNumber));
}
} else if (op == 2) {//动物被收养
if (typeNumber == 0) {//俩队列 选择最小的
if (!dogs.isEmpty() && (cats.isEmpty() || dogs.peek().time < cats.peek().time)) {//只有狗了 或者 狗比 猫进的早
asylum.add(dogs.poll().type);//出队 被收养
}
if (!cats.isEmpty() && (dogs.isEmpty() || dogs.peek().time > cats.peek().time)) {
asylum.add(cats.poll().type);
}
} else if (typeNumber == 1) {//收养狗
if (!dogs.isEmpty()) {
asylum.add(dogs.poll().type);
}
} else if (typeNumber == -1) {//收养猫
if(!cats.isEmpty()){
asylum.add(cats.poll().type);
}
}
} else {
break;
}
}
return asylum;
}
}