Difficulty: Medium
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<int>
如果要用到小顶堆,则一般要把模板的三个参数都带进去。
STL里面定义了一个仿函数 greater<>,对于基本类型可以用这个仿函数声明小顶堆
priority_queue<int, vector<int>, greater<int> >;
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int,vector<int>,greater<int> > heap;
int size=nums.size();
for(int i=0;i<k;++i)
heap.push(nums[i]);
for(int i=k;i<size;++i){
if(heap.top()<nums[i]){
heap.pop();
heap.push(nums[i]);
}
}
return heap.top();
}
};