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.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
题目大意:
给一个无序的数组,要求找到第k大的数字。
思路:
既然找第k大个元素的位置,就是找到第(length-k)个元素,这里可以使用快速排序的思想,快速排序特性是每一趟结束之后可以确定一个元素的位置。
1. 取一个基准p(一般是数组的第一个元素)。
2. 进行快速排序一趟之后可以确定这个基准的最终位置 loc。
3. 如果loc大于(length-k)那就在左边找,否则就在右边找。
public int findKthLargest(int[] nums, int k) {
if(nums.length==0){
return 0;
}
if(k<0 || k>nums.length){
return -1;
}
//上面排除了错误的例子。下面正式开始。
int left=0;
int right=nums.length-1;
int taget=nums.length-k;
int i=0;
while (left<=right){//如果左边小于右边
i=quickSort(nums,left,right); //找到基准的最终的位置
if(i==taget){//如果等于target的话就跳出
break;
}else if(i<taget){//如果i<target的话就在右边找。
left=i+1;
}else {
right=i-1;
}
}
return nums[i];//nums[i]就是我们要找的元素。
}
public int quickSort(int []nums,int left,int right){//返回值是 基准的 最终位置loc。
int tmp;
int i=left;
int j=right;
tmp=nums[left];
while (i!=j){
while (j>i&&nums[j]>tmp) --j;
if(i<j){
nums[i]=nums[j];
++i;
}
while (i<j && nums[i]<tmp) ++i;
if(i<j){
nums[j]=nums[i];
--j;
}
}
nums[i]=tmp;
return i;
}
分析:使用快速排序的思路进行最大值的挑选速度很快。还可以用其他的方法,归并树。