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.

 

求第K大的数

 

C++:快排思想

 1 class Solution {
 2 public:
 3     int findKthLargest(vector<int>& nums, int k) {
 4         k = nums.size() - k ;
 5         int left = 0 ;
 6         int right = nums.size() - 1 ;
 7         while(left < right){
 8             int index = partation(nums,left,right) ;
 9             if (index == k){
10                 break ;
11             }else if(index < k){
12                 left = index + 1 ;
13             }else{
14                 right = index - 1 ;
15             }
16         }
17         return nums[k] ;
18     }
19     
20     int partation(vector<int>& nums, int left , int right) {
21         int k = left ;
22         for(int i = left ; i < right ; i++){
23             if (nums[i] < nums[right]){
24                 swap(nums[k++] , nums[i]) ;
25             }
26         }
27         swap(nums[k] , nums[right]) ;
28         return k ;
29     }
30 };

 

java: 最大堆  求第2大的数可以转化为求第5小的数

 1 class Solution {
 2     public int findKthLargest(int[] nums, int k) {
 3         PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>((o1,o2) -> o2-o1) ;
 4         k = nums.length-k+1 ;
 5         for(int num : nums){
 6             if (minHeap.size() < k){
 7                 minHeap.add(num) ;
 8             }else if(minHeap.peek() > num){
 9                 minHeap.poll() ;
10                 minHeap.add(num) ;
11             }
12         }
13         return minHeap.peek() ;
14     }
15 }

 

posted @ 2019-01-14 15:49  __Meng  阅读(147)  评论(0编辑  收藏  举报