题目描述:
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.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
由于是无序数组,直接排序再求解的时间复杂度为O(nlog n),但是其实我们只需要求第k大的元素即可,所以我们只需要维持一个程度为k的优先队列,遍历一遍数组并进行插入和删除,时间复杂度为O(nlog k)。
class comp{
public:
bool operator()(int a,int b)
{
if(a>b) return true;
else return false;
}
};
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int,vector<int>,comp> q;
for(int i=0;i<nums.size();i++)
{
if(q.size()<k) q.push(nums[i]);
else
{
q.push(nums[i]);
q.pop();
}
}
return q.top();
}
};