快速选择
使用快速排序的partition方法,结合二分查找的思想。
class Solution {
public int findKthLargest(int[] nums, int k) {
if (nums == null || nums.length == 0 || k > nums.length) return 0;
if (nums.length == 1) return 1;
int lo = 0;
int hi = nums.length - 1;
while (lo < hi) {
System.out.println(hi);
int index = partition(nums, lo, hi);
if (index > k - 1) hi = index - 1;
else if (index < k - 1) lo = index + 1;
else return nums[index];
// System.out.println(lo + " " + hi);
}
return nums[k - 1];
}
private int partition(int[] nums, int lo, int hi) {
int pi = nums[lo]; // partitioning item
int i = lo;
int j = hi + 1;
while (true) {
while (nums[++i] > pi) if (i >= hi) break;
while (nums[--j] < pi) if (j <= lo) break;
if (i >= j) break;
exch(nums, i, j);
}
exch(nums, lo, j);
return j;
}
private void exch(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
注意二分搜索的条件为lo < hi,若lo与hi重合,会导致partition时越界。
优先队列
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> queue = new PriorityQueue<>();
for (int num : nums) queue.offer(num);
while (queue.size() > k) queue.poll();
return queue.peek();
}
}