215. Kth Largest Element in an Array

215. Kth Largest Element in an Array

Pick One


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.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.


Seen this question in a real interview before? Yes

No
思路:用最小堆来实现, 当Q的size小于k时,就一直push,而后当堆顶元素小于遍历的nums[i],就给pop出去并且把nums[i] push进入堆中。
AC代码:

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        priority_queue<int,vector<int>,greater<int> >Q;
        for(int i=0;i<nums.size();i++){
            if(Q.size()<k){
                Q.push(nums[i]);
            }
            else if(Q.top()<nums[i]){
                Q.pop();
                Q.push(nums[i]);
            }
        }
        return Q.top();
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容