(lintcode上面的题解)
第k大元素:
(从小到大的排序)
int kthLargestElement(int n, vector<int> &nums) {
// write your code here
return findkth(nums,0,nums.size()-1,nums.size()-n);
}
void swape(vector<int>& nums,int i,int j)
{
int temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
int findkth(vector<int>& nums,int low,int high,int k)
{
int i=low;
int j=high;
int mid=(i+j)/2;
int mid_value=nums[mid];
while(i<j)
{
while(nums[i]<mid_value&&i<=j)
{
i++;
}
while(nums[j]>mid_value&&i<=j)
{
j--;
}
if(i<=j)//也就是上面nums[i]>mid_value&&nums[j]<mid_value,所以要交换
{
swape(nums,i,j);
i++;
j--;
}
}
if(k>i)
return findkth(nums,i,high,k);
if(k<j)
return findkth(nums,low,j,k);
return nums[k];
}
网友评论