我正在做一道练习题
这个问题基本上是你传入一个 PriorityQueue 和某个 k,并且你要返回该 PriorityQueue 中的第 k 个最小值。您还可以将 PriorityQueue 恢复到其初始状态,并可以使用一个堆栈或队列作为辅助数据结构。
我的更高层次的伪想法是,因为 PriorityQueue 已经充当了最小堆,从Java优先级队列 http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html,我真正要做的(我的算法)是:
从 PriorityQueue 中删除 k 个元素
将第 k 个最小值存储为局部变量
将删除的 k 个元素推入堆栈(堆栈,以便我可以按相同顺序添加元素)
从 Stack 中弹出所有元素并将它们重新添加回 PriorityQueue
返回第 k 个最小值
这是完成所有这些操作的代码:
public int kthSmallest(PriorityQueue<Integer> pQ, int k) {
if(k <= 0 || k > pQ.size()) {
throw new IllegalArgumentException();
} else {
Stack<Integer> aux = new Stack<Integer>();
int kThSmallest = -1;
for(int c=0;c<k;c++){
int element = pQ.remove();
if(c == k-1)
kThSmallest = element;
aux.push(element);
}
while(!aux.isEmpty())
pQ.add(aux.pop());
return kThSmallest;
}
}
当我运行该程序时,我得到了所有正确的输出(就第 k 个最小而言),但我无法恢复 PriorityQueue 的状态。例如,当传入以下 PriorityQueue 时:
[-3, 9, 17, 22, 42, 81] with a k of 3
...我的算法产生了正确的结果 17,但它将 PriorityQueue 的状态更改为[-3, 17, 9, 81, 22, 42]
,这是意料之外的。
我考虑过制作 PriorityQueue 的副本,但这违反了一个条件,“您可以使用一个堆栈或队列作为辅助数据结构”。
我怎样才能恢复 PriorityQueue 的状态?