Title Description (medium difficulty)
algorithm
(Small root heap)
(1) using a small root heap, pile whenever there are k + 1 elements, it must not be the top of the stack k-th largest element
(2) traversing the nums array heap will last remaining k elements, At this time, the top element is nums array k-th largest number
Time complexity is , the spatial complexity is
C ++ code 1
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int> > q;
for (auto x : nums) {
q.push(x);
if (q.size() > k) q.pop();
}
return q.top();
}
};
C ++ code 2
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int n = nums.size();
nth_element(nums.begin(), nums.begin() + n - k, nums.end());
return nums[n - k];
}
};