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.
Example 1:
Input: [3,2,1,5,6,4]
and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6]
and k = 4
Output: 4
事实上,这道题 和 选前k小(或大)的元素 是一模一样的。
import java.util.*;
class Solution {
public int findKthLargest(int[] nums, int k) {
shuffle(nums);//乱序
k = nums.length-k; //倒数第k 转为 正数
int low = 0;
int high = nums.length-1;
while(low<high){
int j = partition(nums,low,high);
if(j==k){
break;
}
else if(j<k){
low = j+1;
}
else if(j>k){
high = j-1;
}
}
return nums[k];
}
private int partition(int[] nums,int low,int high){
int i = low;
int j= high+1;
while(true){
while(nums[++i]<nums[low] ){
if(i==high) break;
}
while( nums[low]<nums[--j] ){
// if(j==low) break;
}
if(i>=j){
break;
}
swap(nums,i,j);
}
swap(nums,low,j);
return j;
}
private void swap(int[] nums,int i ,int j){
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
private void shuffle(int nums[]) {
Random random = new Random();
for(int ind = 1; ind < nums.length; ind++) {
int r = random.nextInt(ind + 1);
swap(nums, ind, r);
}
}
}