代码拉取完成,页面将自动刷新
同步操作将从 SE-201/lec07-heap 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
public class Heapmyanswer<T extends Comparable<T>> {
public T[] heap;
public int SIZE;
public int count;
Heapmyanswer(int size) {
SIZE = size;
// reference: https://stackoverflow.com/questions/34827626/cannot-be-cast-to-ljava-lang-comparable
heap = (T[]) new Comparable[SIZE];
count = 0;
}
public class MaxHeap<T extends Comparable<T>> {
private int size;
private int count;
private T[] heap;
public MaxHeap(int size) {
heap = (T[]) new Comparable[size];
this.size = size;
count = 0;
}
// TODO: 完善add函数
public void add(T item) {
if (count == 0) {
heap[count] = item;
} else {
heap[count] = item;
int current = count;
int par = (current - 1) / 2;
while (true) {
if (heap[par].compareTo(heap[current]) < 0) {
replace(par, current);
current = par;
par = (current - 1) / 2;
} else {
break;
}
}
}
count++;
if (count == size) {
T[] array = (T[]) new Comparable[size * 2];
System.arraycopy(heap, 0, array, 0, size);
heap = array;
size *= 2;
}
}
// 完善delete函数
public void delete() {
heap[0] = heap[--count];
heap[count] = null;
int current = 0;
int left = current * 2 + 1;
int right = current * 2 + 2;
while (true) {
if (heap[left] != null && heap[right] != null && heap[current].compareTo(heap[left]) < 0 && heap[current].compareTo(heap[right]) < 0) {
if (heap[left].compareTo(heap[right]) < 0 || heap[left].compareTo(heap[right]) == 0) {
replace(right, current);
current = left;
} else {
replace(left, current);
current = right;
}
left = current * 2 + 1;
right = current * 2 + 2;
} else if (heap[left] != null && heap[current].compareTo(heap[left]) < 0) {
replace(left, current);
current = left;
left = current * 2 + 1;
right = current * 2 + 2;
} else if (heap[right] != null && heap[current].compareTo(heap[right]) < 0) {
replace(right, current);
current = right;
left = current * 2 + 1;
right = current * 2 + 2;
} else {
break;
}
}
}
private void replace(int initial, int target) {
T value;
value = heap[initial];
heap[initial] = heap[target];
heap[target] = value;
}
// 为了测试方便,完善print函数
public void print() {
for (T value : heap) {
if (value == null) {
break;
}
System.out.print(value + " ");
}
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。