面试题 03.06. 动物收容所
采用Java实现。
class AnimalShelf {
public static final int[] ERROR_RESPONSE = {-1, -1};
private Queue<Integer> cat;
private Queue<Integer> dog;
public AnimalShelf() {
cat = new LinkedList<>();
dog = new LinkedList<>();
}
public void enqueue(int[] animal) {
if (animal[1] == 0) {
cat.add(animal[0]);
} else {
dog.add(animal[0]);
}
}
public int[] dequeueAny() {
if (cat.isEmpty() && dog.isEmpty()) {
return ERROR_RESPONSE;
}
if (cat.isEmpty()) {
return new int[]{dog.poll(), 1};
}
if (dog.isEmpty()) {
return new int[]{cat.poll(), 0};
}
if (dog.peek() > cat.peek()) {
return new int[]{cat.poll(), 0};
} else {
return new int[]{dog.poll(), 1};
}
}
public int[] dequeueDog() {
if (dog.isEmpty()) {
return ERROR_RESPONSE;
}
return new int[]{dog.poll(), 1};
}
public int[] dequeueCat() {
if (cat.isEmpty()) {
return ERROR_RESPONSE;
}
return new int[]{cat.poll(), 0};
}
}
/**
* Your AnimalShelf object will be instantiated and called as such:
* AnimalShelf obj = new AnimalShelf();
* obj.enqueue(animal);
* int[] param_2 = obj.dequeueAny();
* int[] param_3 = obj.dequeueDog();
* int[] param_4 = obj.dequeueCat();
*/