215. Kth Largest Element in an Array
2016-05-02 13:36
316 查看
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 [3,2,1,5,6,4] and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.
求数组中的第K大的数字。
第一个思路就是利用快拍的思想,熟悉一下快拍的代码吧
用了两种划分算法,任选一个即可。
另外一种解法就是利用堆排序的特点,每次输出堆顶的元素。
关于STL堆函数的使用参考:/article/1392199.html
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.
求数组中的第K大的数字。
第一个思路就是利用快拍的思想,熟悉一下快拍的代码吧
用了两种划分算法,任选一个即可。
class Solution { public: int partition1(vector<int>& a,int l,int r){ int pivot=a[r]; int i=l-1,j; for(j=l;j<r;j++){ if(a[j]<pivot){ i++; swap(a[i],a[j]); } } swap(a[++i],a[r]); return i; } int partition2(vector<int>& a,int l,int r){ int p=a[r]; while(l<r){ while(l<r&&a[l]<=p){ l++; } a[r]=a[l]; while(l<r&&a[r]>=p){ r--; } a[l]=a[r]; } a[r]=p; return l; } int find(vector<int>& a,int k,int l,int r){ if(l>=r)return a[l]; int tmp=partition2(a,l,r); if(tmp==k)return a[k]; else if(tmp<k) return find(a,k,tmp+1,r); else return find(a,k,l,tmp-1); } int findKthLargest(vector<int>& nums, int k) { return find(nums,nums.size()-k,0,nums.size()-1); } };
另外一种解法就是利用堆排序的特点,每次输出堆顶的元素。
class Solution { public: int findKthLargest(vector<int>& nums, int k) { make_heap(nums.begin(),nums.end()); while(--k){ pop_heap(nums.begin(),nums.end()); nums.pop_back(); } return nums.front(); } };
关于STL堆函数的使用参考:/article/1392199.html
相关文章推荐
- (Caffe)编程小技巧
- 编程:倒数计时器
- 【C语言】 字符串操作函数及内存拷贝函数归总
- maven学习系列5----插件
- iOS程序的生命周期
- 顺序表应用2:多余元素删除之建表算法
- Drawees的设计模式
- 乐观锁和悲观锁的区别
- HDU 4180 扩展欧几里得
- Introduction to algorithm in C++
- [AutoVue开发手册]第二篇——AutoVue之Applet参数列表
- HTop依赖包
- 浪潮之巅阅读笔记一
- 传纸条(一)
- 维护篇 09. 忘记密码或接口 IP ❀ 飞塔 (Fortinet) 防火墙
- 烂泥:zabbix3.0安装与配置
- 交换机和路由器的区别与联系
- c++ unique_ptrs
- [费用流 线段树] BZOJ 3267 KC采花 && 3272 Zgg吃东西 && 3638 Cf172 k-Maximum Subsequence Sum
- RectF Rect用法