有家动物收容所只收容狗与猫,且严格遵照“先进先出”原则。在收养该收容所的动物时,收养人只能收养进入收容所时间最长的动物,或者,挑选猫或狗中收养时间最长的。java
请建立适合这个系统的数据结构,实现各类操做方法,好比enqueue,dequeueAny, dequeDog, dequeueCat等,容许使用Java内置的LinkedList数据结构数据结构
有家动物收容所只收留猫和狗,但有特殊的收养规则,收养人有两种收养方式,第一种为直接收养全部动物中最先进入收容所的,第二种为选择收养的动物类型(猫或狗),并收养该种动物中最先进入收容所的。app
题目分析:测试
根据先进先出的原则,天然想到了用队列实现,若是只维护一个队列,那么第一种方法实现起来比较简单,只须要取出队头的动物则能够,可是第二种方法就比较复杂,须要访问整个队列来找出第一个被访问的猫或者狗。this
所以咱们能够选择维护两个队列来实现,一个队列存放放入的狗,一个队列存放放入的猫,对于第二种方法实现起来至关容易,咱们只须要根据要选择的猫或者狗从 相应的队列中取出即可以,可是第一种方法须要判断那个两个队列头部的是猫先进入收容所,仍是狗先进入,这个时候须要一个标志,因此咱们每次把动物放入队列 的时候,同时将一个递增的序号放入队列,这个序号就是一个时间序列,根据这个序号即可以轻松实现第一种方法。spa
思路:.net
一、方法一:维护一个队列,dequeueAny实现简单,可是dequeueDog和dequeueDog须要迭代访问整个队列,才能找到第一只该被收养的猫或狗。code
二、方法二:blog
[java] view plain copy队列
有家动物收容所只收留猫和狗,但有特殊的收养规则,收养人有两种收养方式,第一种为直接收养全部动物中最先进入收容所的,第二种为选择收养的动物类型(猫或狗),并收养该种动物中最先进入收容所的。
给定一个操做序列int[][2] ope(C++中为vector<vector<int>>)表明全部事件。若第一个元素为1,则表明有动物 进入收容所,第二个元素为动物的编号,正数表明狗,负数表明猫;若第一个元素为2,则表明有人收养动物,第二个元素若为0,则采起第一种收养方式,若为 1,则指定收养狗,若为-1则指定收养猫。请按顺序返回收养的序列。若出现不合法的操做,即没有能够符合领养要求的动物,则将此次领养操做忽略。
测试样例:
[[1,1],[1,-1],[2,0],[2,-1]]
返回:[1,-1]
或者
public
ArrayList<Integer> asylum(
int
[][] ope) {
class
Animal {
int
id, order;
public
Animal(
int
id,
int
order) {
this
.id = id;
this
.order = order;
}
}
int
order =
0
;
LinkedList<Animal> dogs =
new
LinkedList<>();
LinkedList<Animal> cats =
new
LinkedList<>();
ArrayList<Integer> list =
new
ArrayList<>();
for
(
int
i =
0
; i < ope.length; i++) {
if
(ope[i][
0
] ==
1
) {
if
(ope[i][
1
] >
0
)
dogs.add(
new
Animal(ope[i][
1
], order++));
else
if
(ope[i][
1
] <
0
)
cats.add(
new
Animal(ope[i][
1
], order++));
}
else
if
(ope[i][
0
] ==
2
) {
if
(ope[i][
1
] ==
0
) {
Animal d = dogs.peek();
Animal c = cats.peek();
boolean
flag =
false
;
if
(d !=
null
&& c !=
null
) {
if
(d.order - c.order <
0
)
flag =
true
;
}
else
if
(d ==
null
&& c ==
null
)
continue
;
else
if
(d !=
null
)
flag =
true
;
if
(flag)
list.add(dogs.removeFirst().id);
else
list.add(cats.removeFirst().id);
}
else
if
(ope[i][
1
] ==
1
) {
if
(dogs.peek() !=
null
)
list.add(dogs.removeFirst().id);
}
else
if
(ope[i][
1
] == -
1
) {
if
(cats.peek() !=
null
)
list.add(cats.removeFirst().id);
}
}
}
return
list;
}
或者:
import
java.util.*;
public
class
CatDogAsylum {
public
ArrayList<Integer> asylum(
int
[][] ope) {
// write code here
ArrayList<Integer> result =
new
ArrayList<Integer>();
if
(
null
==ope||ope.length<=
0
)
return
result;
ArrayList<Integer> temp =
new
ArrayList<Integer>();
for
(
int
i=
0
;i<ope.length;i++){
if
(ope[i][
0
]==
1
){
//进入
temp.add(ope[i][
1
]);
}
if
(ope[i][
0
]==
2
){
//收养
if
(ope[i][
1
]==
0
&&temp.size()>
0
)
//采用第一种收养方式
result.add(temp.remove(
0
));
else
if
(ope[i][
1
]==-
1
){
//指定收养猫
for
(
int
j=
0
;j<temp.size();j++){
if
(temp.get(j)<
0
){
result.add(temp.remove(j));
break
;
}
}
}
else
if
(ope[i][
1
]==
1
){
//指定收养狗
for
(
int
k=
0
;k<temp.size();k++){
if
(temp.get(k)>
0
){
result.add(temp.remove(k));
break
;
}
}
}
}
}
return
result;
}
}