美文网首页
215. Kth Largest Element in an A

215. Kth Largest Element in an A

作者: 李清依 | 来源:发表于2018-02-28 16:18 被阅读0次

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();
    }
};

相关文章

网友评论

      本文标题:215. Kth Largest Element in an A

      本文链接:https://www.haomeiwen.com/subject/iucixftx.html