leetcode No215. Kth Largest Element in an Array

Question:

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.

Algorithm:

使用优先队列,优先队列是用堆实现(这里是最小堆)当堆得元素超过k个就pop一个,即pop的最小值,这样的操作结束后,优先队列的top值为堆里最小的元素,即整个数组的第k大的值,这里直接用stl实现了。

Accepted Code:

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++){
            q.push(nums[i]);
            if(q.size()>k)
                q.pop();
        }
        return q.top();
    }
};


你可能感兴趣的:(LeetCode)