题目描述
有家动物收容所只收留猫和狗,但有特殊的收养规则,收养人有两种收养方式, * 第一种为直接收养所有动物中最早进入收容所的, * 第二种为选择收养的动物类型(猫或狗),并收养该种动物中最早进入收容所的。 * 给定一个操作序列int[][2] ope(C++中为vector)代表所有事件。 * 若第一个元素为1,则代表有动物进入收容所,第二个元素为动物的编号,正数代表狗,负数代表猫; * 若第一个元素为2,则代表有人收养动物,第二个元素若为0,则采取第一种收养方式(最早), * 若为1,则指定收养狗,若为-1则指定收养猫。 * 请按顺序返回收养的序列。
代码如下
public class CatDogAsylum {
public static ArrayList<Integer> asylum(int[][] ope) {
Queue<Integer> Dog = new LinkedList<>();
Queue<Integer> Cat = new LinkedList<>();
Queue<Integer> All = new LinkedList<>();
Queue<Integer> ToAll = new LinkedList<>();
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < ope.length; i++) {
if(ope[i][0] == 1) {
All.offer(ope[i][1]);
if(ope[i][1] > 0){
Dog.offer(ope[i][1]);
}else if(ope[i][1] < 0){
Cat.offer(ope[i][1]);
}
}else if(ope[i][0] == 2){
if(ope[i][1] == 0){
if(!All.isEmpty()){
Integer tmp = All.poll();
list.add(tmp);
if(tmp.equals(Dog.peek())){
Dog.poll();
}else if (tmp.equals(Cat.peek())){
Cat.poll();
}
}else {
return list;
}
}else if(ope[i][1] == 1){
if(!Dog.isEmpty()){
Integer tmp = Dog.poll();
list.add(tmp);
for (int j = 0; j < All.size();) {
if(All.peek().equals(tmp)){
All.poll();
break;
}else {
ToAll.offer(All.poll());
}
}
int size = All.size();
for (int k = ToAll.size(); k > 0 ; k--) {
All.offer(ToAll.poll());
}
for (int j = 0; j < size; j++) {
All.offer(All.poll());
}
}
}else if(ope[i][1] == -1){
if(!Cat.isEmpty()){
Integer tmp = Cat.poll();
list.add(tmp);
int size = All.size();
for (int j = 0; j < size; j++) {
if(All.peek().equals(tmp)){
All.poll();
break;
}else {
ToAll.offer(All.poll());
}
}
size = All.size();
for (int k = ToAll.size(); k > 0 ; k--) {
All.offer(ToAll.poll());
}
for (int j = 0; j < size; j++) {
All.offer(All.poll());
}
}
}
}
}
return list;
}
|