Description
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.
解题思路
找出数组中第k大元素,遍历数组时将数字加入优先队列,一旦队列的大小大于k就将队列顶元素去除,确保队列的大小为k。遍历完后堆顶就是返回值。时间复杂度为O(nlogk)
代码
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
std::priority_queue<int, std::vector<int>, std::greater<int>> q;
for (auto &v : nums) {
q.push(v);
if (q.size() > k) {
q.pop();
}
}
return q.top();
}
};
注意的是当数小于堆顶且size==k 时不能往堆里加此数值