思路:参考TopK的Quick Select做法https://blog.csdn.net/Somnus_k/article/details/82724704
代码:
public class KthLargestElementinanArray {
public static void main(String[] args) {
int[] arr = { 1, 8, 35, 4, 7 };
System.out.println(findKthLargest(arr, 4));
}
public static int findKthLargest(int[] nums, int k) {
return quickSelect(nums,k,0,nums.length-1);
}
private static int quickSelect(int[] nums, int k, int i, int j) {
if(i>=j)
return nums[i];
int index = partion(nums,i,j);
if(index-i+1==k)
return nums[index];
else if(index-i+1>k)
return quickSelect(nums, k, i, index-1);
else
return quickSelect(nums, k-(index-i+1), index+1, j);
}
private static int partion(int[] nums, int i, int j) {
int tmp = nums[i];
while(i<j){
while(i<j)
if(nums[j]>tmp)
{
nums[i]=nums[j];
i++;
break;
}else
j--;
while(i<j)
if(nums[i]<tmp)
{
nums[j]=nums[i];
j--;
break;
}else
i++;
}
nums[i]=tmp;
return i;
}
}
输出: