【发布时间】:2021-01-13 00:08:00
【问题描述】:
我想在一个数组中找到 K 个最小的元素,并且我基本上能够将我的数组排序为一个最小堆结构,但我仍然得到错误的输出。
这是我的输入:
arr = [9,4,7,1,-2,6,5]
k = 3
这是代码:
public static int[] findKSmallest(int[] arr, int k) {
int[] result = new int[k];
int heapSize = arr.length;
// Write - Your - Code
for (int i = (heapSize - 1) / 2; i >= 0; i--) {
minHeap(arr, i, heapSize);
}
for (int j = 0; j < k; j++) {
result[j] = arr[j];
}
return result;
}
public static void minHeap(int[] arr, int index, int heapSize) {
int smallest = index;
while (smallest < heapSize / 2) {
int left = (2 * index) + 1; // 1 more than half the index
int right = (2 * index) + 2; // 2 more than half the index
if (left < heapSize && arr[left] < arr[index]) {
smallest = left;
}
if (right < heapSize && arr[right] < arr[smallest]) {
smallest = right;
}
if (smallest != index) {
int temp = arr[index];
arr[index] = arr[smallest];
arr[smallest] = temp;
index = smallest;
} else {
break;
}
}
}
这是我的预期输出:
[-2,1,4]
虽然我的输出是:
[-2,1,5]
我想知道我哪里出错了。
【问题讨论】: