0
我使用PriorityQueue
在我的代码中拥有堆数据结构。我不想找到最低价格为cost
的顾客。在执行过程中,客户的成本可能会发生变化。所以我保留了所有客户的堆。我尝试下面的代码 - (输出在评论表示)HeapifyJava priorityQueue
PriorityQueue<Customer> pq = new PriorityQueue<>();
Customer c1 = new Customer(10);
Customer c2 = new Customer(20);
Customer c3 = new Customer(3);
Customer c4 = new Customer(40);
pq.add(c1);pq.add(c2);pq.add(c3);pq.add(c4);
System.out.println(pq.peek() == c3); //Prints true
c1.cost = 1;
System.out.println(pq.peek() == c1); //Prints false
虽然对象c1
的状态改变时,堆没有得到Heapified。基本上我想要两条线都输出true
。我没有找到任何明确Heapifying堆的javadoc帮助。有人可以请帮忙,我该怎么做/调整呢?
据我所见,这是正确的。但是,这不是优先级队列*应该如何工作的方式。更新堆中给定的元素只需要对该元素执行heapUp/heapDown操作(取决于键是增加还是减少),并且运行时间为O(log n)。然而,'remove'调用需要花费时间O(n)来查找要移除的元素......这可能无法摆脱首先使用二进制堆的目的。 – misberner 2014-11-24 11:26:25