堆排序的思想
class Solution {
public:
void swap_element(vector<int>& a, int i, int heapsize){
int l = i * 2 + 1;
int r = i * 2 + 2;
int current = i;
if(l < heapsize && a[l] > a[current]){
current = l;
}
if(r < heapsize && a[r] > a[current]){
current = r;
}
if(current != i){
swap(a[current], a[i]);
swap_element(a, current, heapsize);
}
}
void build_max_heap(vector<int>& a, int heapsize){
for(int i = heapsize / 2; i >= 0; --i){
swap_element(a, i, heapsize);
}
}
int findKthLargest(vector<int>& nums, int k) {
int heapSize = nums.size();
build_max_heap(nums, heapSize);
for(int i = nums.size() - 1; i >= nums.size() - k + 1; --i){
swap(nums[0], nums[i]);
--heapSize;
swap_element(nums, 0, heapSize);
}
return nums[0];
}
};