Medium
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.
解法一:(快排)
最傻瓜快速的解法,直接一次快排,然后返回第len-k位上的值即可。
public int findKthLargest(int[] nums, int k) {
Arrays.sort(nums) ;
return nums[nums.length - k] ;
}
解法二:(小顶堆)
维护一个小顶堆,依次将数组中的元素插入到堆中。因为小顶堆天然保证元素的有序性(从小到大),所以每次在插入元素后检查堆大小是否超过k。如超过,直接移除堆顶(也就是元素值最小的那个)。全部插入完毕后,直接返回堆顶即可。
public int findKthLargest(int[] nums, int k) {
Queue<Integer> heap = new PriorityQueue<>() ;
for(int num : nums) {
heap.add(num) ;
if(heap.size() > k) {
heap.poll() ;
}
}
return heap.poll() ;
}