class Solution {
private:
void swap(vector<int>&nums,int i,int j)
{
int temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
int quickSelect(vector<int>&nums,int l,int r,int k)
{
int temp=nums[r];
int i=l,j=r;
while(i<j)
{
while(i<j&&nums[i]<=temp)
i++;
if(i<j)
swap(nums,i,j);
while(i<j&&nums[j]>=temp)
j--;
if(i<j)
swap(nums,i,j);
}
nums[i]=temp;
int m=i-l+1;
if(k==m)
return i;
else if(k>m)
return quickSelect(nums,i+1,r,k-m);
else
return quickSelect(nums,l,i-1,k);
}
public:
int findKthLargest(vector<int>& nums, int k) {
int p=quickSelect(nums,0,nums.size()-1,nums.size()-k+1);
return nums[p];
}
};
215. Kth Largest Element in an Array
最新推荐文章于 2016-12-03 15:19:40 发布