215. Kth Largest Element in an Array
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.
public class Solution {
public int findKthLargest(int[] nums, int k) {
if (nums.length==1) return nums[0];
int start=0, end= nums.length-1;
int pivot= partition(nums, start, end);
int pos= k-1;
while (pivot != pos){
if (pivot>pos){
end= pivot-1;
pivot= partition(nums, start, end);
} else {
start= pivot+1;
pivot= partition(nums, start, end);
}
}
return nums[pos];
}
private int partition(int[] nums, int start, int end){
if (nums.length==0 || start<0 || end> nums.length) return -1;
int pivot= (int)(start+Math.random()*(end-start));
swapreference(nums, pivot, end);
int big= start-1;
for (pivot= start; pivot< end; pivot++){
if (nums[pivot]>nums[end]){
++big;
if (big!=pivot) swapreference(nums, pivot, big);
}
}
++big;
swapreference(nums, big, end);
return big;
}
private void swapreference(int[] nums, int a, int b){
int tmp= nums[a];
nums[a]= nums[b];
nums[b]= tmp;
}
}