题目:
题解:
void maxHeapify(int* a, int i, int heapSize) {
int l = i * 2 + 1, r = i * 2 + 2, largest = i;
if (l < heapSize && a[l] > a[largest]) {
largest = l;
}
if (r < heapSize && a[r] > a[largest]) {
largest = r;
}
if (largest != i) {
int t = a[i];
a[i] = a[largest], a[largest] = t;
maxHeapify(a, largest, heapSize);
}
}
void buildMaxHeap(int* a, int heapSize) {
for (int i = heapSize / 2; i >= 0; --i) {
maxHeapify(a, i, heapSize);
}
}
int findKthLargest(int* nums, int numsSize, int k) {
int heapSize = numsSize;
buildMaxHeap(nums, heapSize);
for (int i = numsSize - 1; i >= numsSize - k + 1; --i) {
int t = nums[0];
nums[0] = nums[i], nums[i] = t;
--heapSize;
maxHeapify(nums, 0, heapSize);
}
return nums[0];
}