public class Solution {
public int findKthLargest(int[] nums, int k) {
k = nums.length - k;
int left = 0, right = nums.length - 1;
while (left < right) {
int position = partition(nums, left, right);
if (position == k) {
break;
} else if (position < k) {
left = position + 1;
} else {
right = position - 1;
}
}
return nums[k];
}
private int partition(int[] nums, int left, int right) {
int i = left;
int j = right + 1;
int pivot = nums[left];
while (true) {
while (i < right && nums[++i] < pivot);
while (j > left && nums[--j] >= pivot);
if (i >= j) {
break;
}
swap(nums, i, j);
}
swap(nums, left, j);
return j;
}
private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
/*
sort version:
*/
public class Solution {
public int findKthLargest(int[] nums, int k) {
Arrays.sort(nums);
int len = nums.length;
return nums[len - k];
}
}
/*
heap version
*/
public class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<Integer>();
for (Integer i : nums) {
heap.offer(i);
if (heap.size() > k) {
heap.poll();
}
}
return heap.peek();
}
}