java 如何知道在 PriorityQueue 中何时更改了项键以重新堆化已更改的节点
How does java know when in a PriorityQueue , an items key is changed in order to re-heapify the changed node
class PQItem implements Comparable<PQItem>{
public int key;
public PQItem(int key) {
this.key = key;
}
@Override
public int compareTo(PQItem o) {
return this.key - o.key;
}
public String toString(){
return this.key+"";
}
}
PriorityQueue<PQItem> pq = new PriorityQueue<>();
PQItem pq1 = new PQItem(45);
PQItem pq2 = new PQItem(1);
PQItem pq3 = new PQItem(4);
PQItem pq4 = new PQItem(3);
pq.offer(pq1);
pq.offer(pq2);
pq.offer(pq3);
pq.offer(pq4);
pq1.key = 40;
pq2.key = -4;
System.out.println(pq.poll());
System.out.println(pq.poll());
System.out.println(pq.poll());
System.out.println(pq.poll());
以上按预期顺序打印
-4
3个
4个
40
问题是我想知道更改密钥的操作是否在 O(lg n) 中完成,并在已更改的 node.If 上使用 Heapify 完成,java 如何检测我在其中一个对象上设置 属性 以触发该节点上的堆化过程。
它没有,并且在 Javadoc 中特别说明了这一点。
您所做的关键更改恰好是良性的,因为它们不会影响排序。你真是幸运。不要依赖它。
class PQItem implements Comparable<PQItem>{
public int key;
public PQItem(int key) {
this.key = key;
}
@Override
public int compareTo(PQItem o) {
return this.key - o.key;
}
public String toString(){
return this.key+"";
}
}
PriorityQueue<PQItem> pq = new PriorityQueue<>();
PQItem pq1 = new PQItem(45);
PQItem pq2 = new PQItem(1);
PQItem pq3 = new PQItem(4);
PQItem pq4 = new PQItem(3);
pq.offer(pq1);
pq.offer(pq2);
pq.offer(pq3);
pq.offer(pq4);
pq1.key = 40;
pq2.key = -4;
System.out.println(pq.poll());
System.out.println(pq.poll());
System.out.println(pq.poll());
System.out.println(pq.poll());
以上按预期顺序打印 -4 3个 4个 40
问题是我想知道更改密钥的操作是否在 O(lg n) 中完成,并在已更改的 node.If 上使用 Heapify 完成,java 如何检测我在其中一个对象上设置 属性 以触发该节点上的堆化过程。
它没有,并且在 Javadoc 中特别说明了这一点。
您所做的关键更改恰好是良性的,因为它们不会影响排序。你真是幸运。不要依赖它。