问题看起来比较简单,只要进行简单的排序即可,因为标注了堆,就使用了堆进行一下求解:
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: 5Example 2:
Input:[3,2,3,1,2,4,5,5,6]
and k = 4 Output: 4Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
代码为:
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int> q;
for(int i = 0; i < nums.size(); i++)
q.push(nums[i]);
for(int i = 1; i < k; i++)
q.pop();
return q.top();
}
};
用排序函数得到的结果为, 注意vector排序不能写为 sort(nums, nums + nums.size()):
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
return nums[nums.size() - k];
}
};