Problem
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.
思路一(排序取倒数第k个)
- 时间复杂度: O(nlogn)
- 空间复杂度: O(1)
思路二(minHeap)
时间复杂度: O(nlogk)
空间复杂度: O(k)
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>();
for (int i = 0; i < nums.length; i++) {
heap.offer(nums[i]);
if (heap.size() > k) {
heap.poll();
}
}
return heap.peek();
}
思路三(quick select)
时间复杂度: O(n)
空间复杂度: O(1)
public int findKthLargest(int[] nums, int k) {
return quickSelect(nums, 0, nums.length - 1, k);
}
private int quickSelect(int[] nums, int start, int end, int k) {
if (start >= end) {
return nums[start];
}
int left = start;
int right = end;
int pivot = nums[(left + right) / 2];
while (left <= right) {
while (left <= right && nums[left] > pivot) left++;
while (left <= right && nums[right] < pivot) right--;
if (left <= right) {
int temp = nums[left];
nums[left++] = nums[right];
nums[right--] = temp;
}
}
if (start + k - 1 <= right) {
return quickSelect(nums, start, right, k);
}
if (start + k - 1 >= left) {
return quickSelect(nums, left, end, k - (left - start));
}
return nums[right + 1];
}