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.
1 public class Solution { 2 public int findKthLargest(int[] nums, int k) { 3 Arrays.sort(nums); 4 return nums[nums.length-k]; 5 } 6 }
解法二:
维护一个大小为k 的最小堆,遍历一遍数组,再返回最小堆的顶部元素即为第k大元素。
1 public class Solution { 2 public int findKthLargest(int[] nums, int k) { 3 PriorityQueue<Integer> q = new PriorityQueue<Integer>(k+1); 4 for(int n : nums){ 5 q.offer(n); 6 if(q.size() > k) q.poll(); 7 } 8 return q.poll(); 9 } 10 }
解法三: 又看到使用quickseleck 做的O(n),二刷再试下。