215. Kth Largest Element in an Array

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: 5

Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

Note: 
You may assume k is always valid, 1 ≤ k ≤ array's length.


 

关键字:Kth largest element, 最大(小)的K值,用priority queue来做。Priority queue重点是partial ordering, top element是最值。  
求第K个的值,也就是K个最大值中的最小的那个值,需要一个size为K的最堆:

1st, 2nd, 3rd, ...., Kth, .................. n th (largest) 


template <class T, class Container = vector<T>, class Compare = less<typename Container::value_type> > class priority_queue;

Priority queue in C++ by default uses std::less as comparator and is a max-heap.  

 1 class Solution {
 2 public:
 3     int findKthLargest(vector<int>& nums, int k) {
 4         //We need a min-heap, note: by default C++ using "less" comparator and is a max-heap
 5         priority_queue<int,vector<int>,greater<int>> pq; 
 6         
 7         for(int num: nums){
 8             //maintain a min-heap of size K to store K largest elements, the top element is the kth largest number
 9             if(pq.size()<k){ //heap size is less than K
10                 pq.push(num);
11             }else{
12                 if(num>pq.top()){ //current num is larger than Kth largest in the heap
13                     pq.pop();
14                     pq.push(num);
15                 }
16             }
17         }
18         return pq.top();
19     }
20 };

 

posted @ 2018-07-05 04:08  回到明天  阅读(92)  评论(0)    收藏  举报