Difficulty: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.
For example,
Given [3,2,1,5,6,4]
and k = 2, return 5.
题目要求找到第K小的数,并且要求了时间复杂度在O( n)之内,之前解决过在log n时间复杂度的范围内找到最小的数目,使用了二分搜索的方法,但是很明显这个题目中是不符合要求的,因为还没有进行排序。所以就考虑使用快速排序的思路,在函数的内部其实与快速排序是相同的,只需要每次划分分治的时候判断当前key的值与k的大小,这样就可以省去一半的时间,当最后,恰好找到了某个数字的下标,因为对于k,之前的所有数字是小于arr[k]的
代码如下:
int quick(vector<int>& arr,int left,int right,int k,int sum)
{
int x=left;int y=right;
int key=arr[left];
while(x<y)
{
while(key<=arr[y]&&x<y)
{
y--;
}
if(x<y)arr[x++]=arr[y];
while(key>arr[x]&&x<y)
{
x++;
}
if(x<y)arr[y--]=arr[x];
}
arr[x]=key;
if(sum-x==k) return key;
else if(sum-x>k)return quick(arr,x+1,right,k,sum);
else return quick(arr,left,x-1,k,sum);
return 0;
}
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int left=0;int right=nums.size();
int ans=0;
ans=quick(nums,left,right-1,k,right);
return ans;
}
};