Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4]
and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
用priority_queue,定义小端队列,priority_queue<int, vector<int>, greater<int>>,小的元素先出列,队头为最小元素,也即第K大元素
遍历nums数组,当队列大小为k的时候如果i>topK.top(),队列弹出队头,把i放进去,否则跳过元素i
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int, vector<int>, greater<int>> topK;
for (auto i : nums)
{
if (topK.size() == k)
{
if (topK.top() >= i)
continue;
topK.pop();
}
topK.push(i);
}
return topK.top();
}
};