Java中的MaxHeap实现不需要';我不能正常工作
我通过扩展ArrayList实现了Heap。然而,它似乎和minheap一样工作良好(与此代码几乎没有区别),但它不能像maxheap一样正常工作。我想我有一个或多个零件用错了。我想知道什么是错的或被误解了 如果有更好的方法,我会非常感谢你的评论,谢谢Java中的MaxHeap实现不需要';我不能正常工作,java,algorithm,heap,Java,Algorithm,Heap,我通过扩展ArrayList实现了Heap。然而,它似乎和minheap一样工作良好(与此代码几乎没有区别),但它不能像maxheap一样正常工作。我想我有一个或多个零件用错了。我想知道什么是错的或被误解了 如果有更好的方法,我会非常感谢你的评论,谢谢 class Heap<T extends Comparable<T>> extends ArrayList<T> { public void insert(T elem) { th
class Heap<T extends Comparable<T>> extends ArrayList<T> {
public void insert(T elem) {
this.add(elem);
int idx = this.size() - 1;
if(idx > 0 && this.compare(idx, (idx - 1) / 2)){
Collections.swap(this, idx, (idx - 1) / 2);
idx = (idx - 1) / 2;
}
}
public void removeTop() {
if(this.size() == 1) {
this.remove(0);
return;
}
this.set(0, this.remove(this.size() - 1));
int here = 0;
while(true) {
int left = here * 2 + 1;
int right = here * 2 + 2;
if(left >= this.size()) break;
int next = here;
if(!this.compare(next, left)) {
next = left;
}
if(right < this.size() && !this.compare(next, right)){
next = right;
}
if(next == here) break;
Collections.swap(this, next, here);
here = next;
}
}
private void swap(int idx1, int idx2) {
T temp = this.get(idx1);
this.set(idx1, this.get(idx2));
this.set(idx2, temp);
}
private boolean compare(int idx1, int idx2) {
return this.get(idx1).compareTo(this.get(idx2)) >= 0;
}
}
在Java中是否可以使用比较器?使用比较器:
class Heap<T> extends ArrayList<T> {
private final Comparator<T> comparator;
public Heap(Comparator<T> comparator) {
this.comparator = comparator;
}
您可以这样创建堆
:
Heap<Integer> heap = new Heap<Integer>((a,b) -> a.compareTo(b));
Heap-Heap=新堆((a,b)->a.compareTo(b));
(这方面的例子已经够多了。我错过了remove()
,以防size()!=1
)compare()
是noLess()
的一个糟糕名称。灰胡子谢谢你的评论:)顺便说一下,这意味着有足够多的实例。
您遗漏了什么?我首先评论了调用remove()
missing时size()!=1
:没有在this.set(0,this.remove(this.size()-1))
中发现它,这可以很容易地set(0,remove(size()-1))
。是的,当大小为1时,this.set(0,…)
部分抛出绑定异常的索引。谢谢!顺便问一下,在compare
方法中使用这个可以吗<代码>返回比较器。比较(get(idx1),get(idx2))>=0在这个上面使用get(idx1)是否更好。get(idx1)除了简洁之外?@JasonPark这是一样的,它将生成相同的代码。
private boolean compare(int idx1, int idx2) {
return comparator.compare(get(idx1), get(idx2)) >= 0;
}
}
Heap<Integer> heap = new Heap<Integer>((a,b) -> a.compareTo(b));