您的位置:首页 > 其它

leetcode 215: Kth Largest Element in an Array

2015-08-28 11:05 363 查看
Use quick sort.

This is the 8ms version. With the sorting of the whole array, the time is long.

class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int n=nums.size();
quicksort(nums,0,n-1);
return nums[k-1];
}
void quicksort(vector<int>& nums,int L,int R)
{
int l=L,r=R;
int key=nums[l];
while(l<r)
{
while(l<r&&nums[r]<key)
r--;
nums[l]=nums[r];
while(l<r&&nums[l]>=key)
l++;
nums[r]=nums[l];
}
nums[l]=key;
if(l-1>L)
quicksort(nums,L,l-1);
if(l+1<R)
quicksort(nums,l+1,R);
}
};

This is the 4ms version, I learned it from http://www.cnblogs.com/easonliu/p/4523941.html. It does not sort the whole array to find the number. Just sort the correct range is ok.

class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int n=nums.size();
int L=0,R=n-1;
while (L<R) {
int l=L,r=R;
int key=nums[l];
while (l<r) {
while (l<r&&nums[r]<key)
r--;
nums[l]=nums[r];
while (l<r&&nums[l]>=key)
l++;
nums[r]=nums[l];
}
nums[l]=key;
//do not have to sort the whole array, just sort the range with k-1 inside
if (l==k-1) return nums[k - 1];
else if (l>k-1) R=l-1;
else L=l+1;
}
return nums[k-1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: