【发布时间】:2020-09-09 12:12:18
【问题描述】:
从 1 到 n 的数字按一定顺序添加到最小堆中。对于每个数字,找出它在最小堆中改变位置的次数。
澄清:对于添加使用方法Insert(),添加节点的顺序与它们在输入中的顺序相同。
输入:第一行是数字n。在第二行,除以空格,是从 1 到 n 的 n 个数字。
输出:n个数除以空格:第i个数表示第i个数在构建的最小堆中的位置变化次数。
即5 4 3 2 1
回答 2 3 3 2 2
public class MinHeap {
private int[] heap;
private int size;
private int maxsize;
public MinHeap(int maxsize) {
this.maxsize = maxsize;
this.size = 0;
heap = new int[this.maxsize + 1];
heap[0] = Integer.MIN_VALUE;
}
private void swap(int fpos, int spos) {
int tmp;
tmp = heap[fpos];
heap[fpos] = heap[spos];
heap[spos] = tmp;
}
private void minHeapify(int pos) {
if (2 * pos == size) {
if (heap[pos] > heap[2 * pos]) {
swap(pos, 2 * pos);
minHeapify(2 * pos);
}
return;
}
if (2 * pos <= size) {
if (heap[pos] > heap[2 * pos] || heap[pos] > heap[2 * pos + 1]) {
if (heap[2 * pos] < heap[2 * pos + 1]) {
swap(pos, 2 * pos);
minHeapify(2 * pos);
}
else {
swap(pos, 2 * pos + 1);
minHeapify(2 * pos + 1);
}
}
}
}
public void insert(int element) {
heap[++size] = element;
int current = size;
while (heap[current] < heap[current / 2]) {
swap(current, current / 2);
current = current / 2;
}
}
public void minHeap() {
for (int pos = (size / 2); pos >= 1; pos--) {
minHeapify(pos);
}
}
public int extractMin() {
if (size == 0) {
throw new NoSuchElementException("Heap is empty");
}
int popped = heap[1];
heap[1] = heap[size--];
minHeapify(1);
return popped;
}
}
我不会数数
【问题讨论】:
-
您的堆实现将根放在数组中的索引 1 处。数组从 0 开始,如果您使用 Java 等基于 0 的语言构建堆,则堆应该从 0 开始。请参阅stackoverflow.com/a/49806133/56778