题目描述
有家动物收容所只收留猫和狗,但有特殊的收养规则,收养人有两种收养方式,第一种为直接收养所有动物中最早进入收容所的,第二种为选择收养的动物类型(猫或狗),并收养该种动物中最早进入收容所的。
给定一个操作序列int[][2] ope(C++中为vector<vector<int>>)代表所有事件。若第一个元素为1,则代表有动物进入收容所,第二个元素为动物的编号,正数代表狗,负数代表猫;若第一个元素为2,则代表有人收养动物,第二个元素若为0,则采取第一种收养方式,若为1,则指定收养狗,若为-1则指定收养猫。请按顺序返回收养的序列。若出现不合法的操作,即没有可以符合领养要求的动物,则将这次领养操作忽略。
测试样例:
[[1,1],[1,-1],[2,0],[2,-1]]
返回:[1,-1]
根据题目我们可以选择维护两个队列来实现,一个队列存放放入的狗,一个队列存放放入的猫,对于第二种方法实现起来相当容易,我们只需要根据要选择的猫或者狗从相应的队列中取出便可以,再用第三个队列来表示总的动物
代码如下:
package com.mianshi;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class jingdian_17 {
public static void main(String[] args) {
int[][] ope = new int[][] { { 1, 1 }, { 1, -1 }, { 2, 0 }, { 2, -1 } };
ArrayList<Integer> list = jingdian_17.asylum(ope);
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
}
public static ArrayList<Integer> asylum(int[][] ope) {
Queue<Integer> dog = new LinkedList<Integer>();
Queue<Integer> cat = new LinkedList<Integer>();
Queue<Integer> all = new LinkedList<Integer>();
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < ope.length; i++) {
// 表示收留动物
if (ope[i][0] == 1) {
if (ope[i][1] > 0) {
// >0表示收留的狗
all.add(ope[i][1]);
dog.add(ope[i][1]);
} else if (ope[i][1] < 0) {
all.add(ope[i][1]);
cat.add(ope[i][1]);
}
} else if (ope[i][0] == 2) {// 表示收养动物
// 0表示先收留的线收养
if (ope[i][1] == 0) {
if (!all.isEmpty()) {
int temp = all.poll();
list.add(temp);
// 同步删除狗队列或者猫队列中的元素
if (temp > 0) {
dog.poll();
} else {
cat.poll();
}
}
} else if (ope[i][1] > 0) {// 表示在狗队列里面收养最先收留的狗
// 还是要先判断一下狗队列里面是否有狗
if (!dog.isEmpty()) {
int temp = dog.poll();
list.add(temp);
// 删除all里面的狗
all.remove(temp);
}
} else {// 表示在猫队列里面收养最先收留的猫
if (!cat.isEmpty()) {
int temp = cat.poll();
list.add(temp);
// 删除all里面的猫
all.remove(temp);
}
}
}
}
return list;
}
}