在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
示例 1:
输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
示例 2:
输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
说明:
你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。
解题思路
利用快速排序的思想,在第一次交换完成后,以第一个元素为基准,从基准位置将数组分为左右两部分,假设返回的位置为pos,那么基准元素就是数组中第pos大的元素,此时比较数组长度-pos和k大小,大于k,说明第k大的数在基准的右侧,则递归调用排序在右侧查找,反之在左侧。
class Solution {
public int findKthLargest(int[] nums, int k) {
return quickSort(0,nums.length-1,nums,k);
}
int quickSort(int low,int high,int[] temp,int k)
{
if(low>=high)return temp[low];//递归结束的约束条件
int point=partition(low,high,temp);//每一次分割后“轴”的下标
if(temp.length-point==k) return temp[point];
else if(temp.length-point>k){
return quickSort(point+1,high,temp,k);
}
else{
return quickSort(low,point-1,temp,k);
}
}
public int partition(int low,int high,int[] temp)//采用分治的思想
{
int cur=temp[low];
while(low<high)
{
while(low<high&&temp[high]>=cur)
--high;
temp[low]=temp[high];
while(low<high&&temp[low]<=cur)
++low;
temp[high]=temp[low];
}
temp[low]=cur;
return low;
}
}