classSolution { private: voidheapify(vector<int> &vec, int curr, int n) { int left = curr * 2 + 1; int right = curr * 2 + 2; int largest = curr;
if (left < n && vec[left] > vec[largest]) { largest = left; }
if (right < n && vec[right] > vec[largest]) { largest = right; }
if (largest != curr) { std::swap(vec[largest], vec[curr]); //Since the parent and child nodes have been swapped, it may affect the subtree of the child node, so adjust the subtree of the child node. heapify(vec, largest, n); } }
voidbuildMaxHeap(vector<int> &vec) { int n = vec.size(); // The position of the last node is n-1, so the position of the parent node is (n-1-1)/2. for (int i = (n - 2) / 2; i >= 0; i--) { heapify(vec, i, n); } }
public: intfindKthLargest(vector<int> &nums, int k) { int n = nums.size(); buildMaxHeap(nums);
for (int i = 0; i < k - 1; i++) { // pop std::swap(nums[0], nums[n - 1]); n--; heapify(nums, 0, n); } return nums[0]; } };
Quick sort
Note that the Hoare partition scheme does not care where elements equal to the pivot are, only requires left <= pivot and right >= pivot.
#include<vector> using std::vector; classSolution { private: intquick_sort(vector<int> &nums, int start, int end, int k) { if (end <= start) { return nums[k]; } int pivot = nums[(start + end) / 2]; int left = start - 1; int right = end + 1; while (left < right) { do { left++; } while (nums[left] < pivot); do { right--; } while (nums[right] > pivot); if (left < right) { std::swap(nums[left], nums[right]); } } // start..=right, right+1..=end if (k<= right) { returnquick_sort(nums, start, right, k); } else { returnquick_sort(nums, right+1, end, k); } }
public: intfindKthLargest(vector<int> &nums, int k) { int n = nums.size(); // The K-th largest is the (n-k)-th smallest. returnquick_sort(nums, 0, n - 1, n - k); } };