寻找第K大的数字,基本思路和快速排序一样,一趟快速排序后返回的值就是已经排好的数字的个数。
如果返回值需要的个数,那么在之前的一小段中找到最大的值(因为没有像快排那样,前半的也排序)
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
k = nums.size() - k + 1;
return select(nums,0,nums.size()-1,k);
}
private:
int paritition(vector<int>& arr,int left,int right)
{
int pivot = arr[(left+right)/2];
while(left <= right)
{
while(arr[left] < pivot) left++;
while(arr[right] > pivot) right--;
if(left <= right)
{
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
return left;
}
int select(vector<int>& nums,int left,int right,int k)
{
int index = paritition(nums,left,right);
int k_index = index - left;
if(k == k_index)
{
int mmax = numeric_limits<int>::min();
for(int i = left;i<index;i++)
mmax = mmax>nums[i]?mmax:nums[i];
return mmax;
}
if(k < k_index)
return select(nums,left,index-1,k);
else if(k > k_index)
return select(nums,index,right,k-k_index);
}
};