题目描述(中等难度)
算法
(小根堆)
(1)使用小根堆,每当堆中有 k + 1 个元素时,那栈顶一定不可能是第 k 大的元素
(2)遍历这个nums数组,最后堆中会剩下 k 个元素,此时栈顶元素就是nums数组中第 k 大的数
时间复杂度是 ,空间复杂度是
C++代码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++代码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];
}
};