leetcode-Kth Largest Element in an Array
2015-11-11 12:09
267 查看
Difficulty: Medium
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.
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.
参数缺省的话,优先队列就是大顶堆,队头元素最大 priority_queue<int>
如果要用到小顶堆,则一般要把模板的三个参数都带进去。 STL里面定义了一个仿函数 greater<>,对于基本类型可以用这个仿函数声明小顶堆 priority_queue<int, vector<int>, greater<int> >;
class Solution { public: int findKthLargest(vector<int>& nums, int k) { priority_queue<int,vector<int>,greater<int> > heap; int size=nums.size(); for(int i=0;i<k;++i) heap.push(nums[i]); for(int i=k;i<size;++i){ if(heap.top()<nums[i]){ heap.pop(); heap.push(nums[i]); } } return heap.top(); } };
相关文章推荐
- golang中container/ring包用法
- hive 中复杂类型的使用
- TortoiseGit的安装使用
- Android AsyncTask完全解析
- about golang
- 网页设计图片素材网站 收集
- git安装及使用
- 使用ssh private key 免密码登陆服务器的流程(Amazon 的EMR 采用了此方式登陆服务器)
- Hibernate主键生成策略
- org.springframework.jdbc.UncategorizedSQLException: Error setting null parameter.
- 几个关于控件的优先级: UseSystemPasswordChar > PasswordChar > 控件属性设置
- 监听鼠标上下滚动事件
- 简单日志集成
- 【翻译】PHP7——新特性
- asp.net 获取客户端真实Ip
- web 前端学习网站 收集
- linux gdb运行不下去的程序调试方法
- Android-->AndroidManifest.xml 文件 <meta-data> 使用方法
- java编程思想向上转型例子
- does not contain bitcode. You must rebuild it