classSolution { public: intfindKthLargest(vector<int>& nums, int k){ int size = nums.size(); buildHeap(nums, size); for (int i = nums.size() - 1; i >= nums.size() - k + 1; --i) { swap(nums[0], nums[i]); --size; maxify(nums, 0, size); } return nums[0]; }
private: voidbuildHeap(vector<int>& a, int size){ for(int i = size / 2; i >= 0; --i) { maxify(a, i, size); } } voidmaxify(vector<int>& a, int i, int size){ int l = i * 2 + 1, r = i * 2 + 2, max = i; if(l < size && a[l] > a[max]) max = l; if(r < size && a[r] > a[max]) max = r; if(max != i ) { swap(a[i], a[max]); maxify(a, max, size); } } };
funcpartition(nums []int, left int, right int, k int)int { if left == right { return nums[left] } p := right l := left r := right-1 for l <= r { for (l <= r && nums[l] >= nums[p]) { l++ } for (l <= r && nums[r] < nums[p]) { r-- } if (l <= r) { nums[l], nums[r] = nums[r], nums[l] l++ r-- } } nums[l], nums[p] = nums[p], nums[l] p = l if (p > k-1) { return partition(nums, left, p-1, k) } elseif (p < k-1) { return partition(nums, p+1, right, k) } return nums[p]; }