Level:
Medium
题目描述:
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
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
思路分析:
题目要求找出未排序数组的第K个最大的数,我们可以转换为找从小到大排列的第n-k个数。我们使用快速排序的partition函数,partition函数选择一个flag值,将数组中小于flag的值放在flag左边,将大于flag的值放在右边,我们要找第n-k个数,可以通过判断flag的位置确定,如果flag的位置正好是n-k,那我们找到答案,否则我们可以将范围缩小继续查找。
代码:
public class Solution{
public int findKthLargest(int[] nums,int k){
int n=nums.length-k;
int low=0;
int high=nums.length-1;
int t;
while(low<high){
t=partition(nums,low,high);
if(t>n){
high=t-1;
}else if(t<n){
low=t+1;
}else{
break;
}
}
return nums[n];
}
public int partition(int []nums,int low,int high){
int key=nums[low];
while(low<high){
while(low<high&&nums[high]>=key){
high--;
}
nums[low]=nums[high];
while(low<high&&nums[low]<=key){
low++;
}
nums[high]=nums[low];
}
nums[low]=key;
return low;
}
}