1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class Solution{ public: void heap_sort(vector<int>&ans, int i, int n) { int l = i * 2 + 1, r = i * 2 + 2, max = i; if (l < n && ans[l] > ans[max]) max = l; if (r < n && ans[r] > ans[max]) max = r; if (max != i) { swap(ans[i], ans[max]); heap_sort(ans, max, n); } }
void buildHeap(vector<int>& ans, int n) { for (int i = n / 2; i >= 0; --i) heap_sort(ans, i, n); }
int findKthLargest(vector<int>& nums, int k) { int n = nums.size(); buildHeap(nums, n); for (int i = nums.size() - 1; i >= nums.size() - k + 1; i--) { swap(nums[0], nums[i]); --n; heap_sort(nums, 0, n); } return nums[0]; } };
|