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.
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];
}
};
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];
}
};
相关文章推荐
- 常用库和Xcode插件
- java+Struts2生成验证码
- 图像分割之(二)Graph Cut(图割)
- CF 358 D Dima and Hares(dp)
- 关于VBS连接MySQL与连接Excel
- 百度pc wap适配
- [LeetCode] 9 - Palindrome Number
- android中activity,window,view之间的关系
- js实现显示当前状态的导航效果代码
- 完全背包——方案个数 UVA11137 Ingenuous Cubrency
- Maven介绍
- C语言中操作密码文件的一些函数总结
- 服务器tcp连接timewait过多优化及详细分析
- 说说微信支付那点事
- 图像分割之(一)概述
- Lua中的九九乘法表以及字符串拼接
- c++中的rand函数
- Mac环境下svn的使用
- 人生职业规划
- DNS从服务器迁移(基于windows为主,linux为从实现同步)