Leetcode[215]-Kth Largest Element in an Array
2015-06-13 20:58
489 查看
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given
Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
法一:使用STL的sort排序O(NlogN)
法二:自己写快速排序O(NlogN)
法三:使用建堆法 时间复杂度O(klogN)
方法四:此方法是论坛看到的,O(N)
For example,
Given
[3,2,1,5,6,4]and
k = 2, return
5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
法一:使用STL的sort排序O(NlogN)
int findKthLargest(vector<int>& nums, int k) { sort(nums.begin(),nums.end()); return nums[nums.size()-k]; }
法二:自己写快速排序O(NlogN)
int findKthLargest(vector<int>& nums, int k){ quickSort(nums, 0 ,nums.size()); return nums[nums.size()-k]; } void quickSort(vector<int> &nums, int left, int right){ int i = left, j = right - 1; if(i < j){ int po = nums[i]; while(i < j){ while(i < j && nums[j] >= po) j--; if(i < j) { nums[i++] = nums[j]; } while(i < j && nums[i] <= po ) i++; if(i < j){ nums[j--] = nums[i]; } } nums[i] = po; quickSort(nums, left, i); quickSort(nums, i+1, right); } }
法三:使用建堆法 时间复杂度O(klogN)
int findKthLargest(vector<int>& nums, int k){ make_heap(nums.begin(), nums.end()); for(auto i=0; i<k-1;i++){ pop_heap(nums.begin(), nums.end()); nums.pop_back(); } return nums.front(); }
方法四:此方法是论坛看到的,O(N)
int findKthLargest(vector<int>& nums, int k){ int i, m, n, pivot, head =0, tail = nums.size()-1, maxV; while(1){ m = head, n= tail; pivot = nums[m++]; while(m <= n) { if(nums[m] >= pivot) m++; else if(nums < pivot) n--; else { swap(nums[m++], nums[n--]); } } if(m-head == k) return pivot; else if(m-head < k) { k -= (m-head); head = m; } else { tail = m-1; head = head+1; } } }
相关文章推荐
- android自定义控件(三) 增加内容 自定义属性 format详解
- android自定义控件(三) 自定义属性
- S5PV210开发系列一_开发环境以及启动模式
- android自定义控件(二) 入门,继承View
- 解析JSON的过程
- android自定义控件(一) 官方文档的翻译
- IP - SRAM
- Uva - 230 - Borrowers
- Uva - 230 - Borrowers
- Codeforces 551B ZgukistringZ (字符串处理)
- MYSQL查询性能优化
- CentOS下安装postgresql 9.4
- Hadoop开发常用的InputFormat和OutputFormat
- JavaScript控制XML文件数据
- 全面解析Java类加载器
- ubuntu下使用Github
- 认识自己——不要自作多情ZP
- PHP上传文件设计分析
- Linux数据流重定向
- 什么叫面向对象?