面试题 03.06. 动物收容所

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class AnimalShelf {

private final List<Queue<Integer>> queueList;
private final int CAT_QUEUE_INDEX = 0;
private final int DOG_QUEUE_INDEX = 1;

public AnimalShelf() {
this.queueList = new ArrayList<>(2);
this.queueList.add(new LinkedList<>()); // cat
this.queueList.add(new LinkedList<>()); // dog
}

public void enqueue(int[] animal) {
queueList.get(animal[1]).offer(animal[0]);
}

public int[] dequeueAny() {
if (!queueList.get(CAT_QUEUE_INDEX).isEmpty() && !queueList.get(DOG_QUEUE_INDEX).isEmpty()) {
if (queueList.get(CAT_QUEUE_INDEX).peek() <= queueList.get(DOG_QUEUE_INDEX).peek()) {
return new int[]{queueList.get(CAT_QUEUE_INDEX).poll(), CAT_QUEUE_INDEX};
} else {
return new int[]{queueList.get(DOG_QUEUE_INDEX).poll(), DOG_QUEUE_INDEX};
}
}

for (int i = 0; i < queueList.size(); i++) {
Queue<Integer> queue = queueList.get(i);
if (!queue.isEmpty()) {
return dequeueByType(i);
}
}

return new int[]{-1, -1};
}

public int[] dequeueDog() {
return dequeueByType(DOG_QUEUE_INDEX);
}

private int[] dequeueByType(int queueIndex) {
Queue<Integer> catQueue = queueList.get(queueIndex);
if (catQueue.isEmpty()) {
return new int[]{-1, -1};
} else {
return new int[]{catQueue.poll(), queueIndex};
}
}

public int[] dequeueCat() {
return dequeueByType(CAT_QUEUE_INDEX);
}

}

该题题意表述不明,意义不大。

References

面试题 03.06. 动物收容所