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.
Solution
The naive way of doing this is to sort the array nums and then return nums[nums.length - k].O(NlogN)
Further, we can do better by using a Priority Queue, which has complexity of O(NlogK):
1
2
3
4
5
6
7
8
9
10
11
12
publicclassSolution{
publicintfindKthLargest(int[] nums, int k){
PriorityQueue<Integer> pq = new PriorityQueue<>(k + 1);
for (int num : nums) {
pq.offer(num);
if (pq.size() > k) {
pq.poll();
}
}
return pq.peek();
}
}
Better, use quick select. The basic idea is like quick sort to partition the array by a pivot. Compare the index of pivot with k to decide which part to go.