优化TOP k问题
TOP k问题是常见的排序问题,利用堆排序,求大量待排序数据中的最大或最小若干项。
代码求解部分如下:
public int findKthLargest(int[] nums, int k) {
int[] heap = new int[k + 1];
Arrays.fill(heap, Integer.MIN_VALUE / 2);
for (Integer each : nums) {
if (each < heap[1]) continue;
heap[1] = each;
sink(heap, 1, k);
}
return heap[1];
}
public void sink(int[] nums, int k, int N) {
while (2 * k <= N) {
int j = 2 * k;
if (j < N && less(nums, j, j + 1)) j++;
if (!less(nums, k, j)) break;
swap(nums, k, j);
k = j;
}
}
public void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
public boolean less(int[] nums, int i, int j) {
return nums[j] - nums[i] < 0;
}