title: 最小的 date: 2019-08-21T11:00:41+08:00 draft: false categories: offer
public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
ArrayList<Integer> res = new ArrayList<>();
if (k > input.length || k == 0) {
return res;
}
for (int i = input.length - 1; i >= 0; i--) {
minHeap(input, 0, i);
swap(input, 0, i);
res.add(input[i]);
if (res.size() == k) break;
}
return res;
}
private void minHeap(int[] heap, int start, int end) {
if (start == end) {
return;
}
int childLeft = start * 2 + 1;
int childRight = childLeft + 1;
if (childLeft <= end) {
minHeap(heap, childLeft, end);
if (heap[childLeft] < heap[start]) {
swap(heap, start, childLeft);
}
}
if (childRight <= end) {
minHeap(heap, childRight, end);
if (heap[childRight] < heap[start]) {
swap(heap, start, childRight);
}
}
}
private void swap(int[] nums, int a, int b) {
int t = nums[a];
nums[a] = nums[b];
nums[b] = t;
}