class Solution {
public void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
public void buildMaxHeap(int[] a, int i, int length) {
int l = (i << 1) + 1;
int r = l + 1;
int maxId = i;
if (l < length && a[l] > a[maxId]) {
maxId = l;
}
if (r < length && a[r] > a[maxId]) {
maxId = r;
}
if (maxId == i) return;
swap(a, i, maxId);
buildMaxHeap(a, maxId, length);
}
public void getMax(int[] a, int length) {
swap(a, length - 1, 0);
length --;
buildMaxHeap(a, 0, length);
}
public int findKthLargest(int[] nums, int k) {
for (int i = nums.length / 2; i >= 0; i --) {
buildMaxHeap(nums, i, nums.length);
}
for (int i = 0; i < k - 1; i ++) {
getMax(nums, nums.length - i);
}
return nums[0];
}
}
LeetCode刷题记205-Heap(堆)
最新推荐文章于 2022-10-30 10:27:27 发布