基于快速排序:

 class Solution {
public:
/*
* param k : description of k
* param nums : description of array and index 0 ~ n-1
* return: description of return
*/
int kthLargestElement(int k, vector<int> nums) {
// write your code here
int left = , right = nums.size() - ;
while (true) {
int pos = partition(nums, left, right);
if (pos == k - ) return nums[pos];
if (pos < k - ) left = pos + ;
if (pos > k - ) right = pos - ;
}
}
private:
int partition(vector<int>& nums, int left, int right) {
int pivot = nums[left];
int l = left + , r = right;
while (l <= r) {
if (nums[l] < pivot && nums[r] > pivot)
swap(nums[l++], nums[r--]);
if (nums[l] >= pivot) l++;
if (nums[r] <= pivot) r--;
}
swap(nums[left], nums[r]);
return r;
}
};

基于最大堆:

 class Solution {
public:
/*
* param k : description of k
* param nums : description of array and index 0 ~ n-1
* return: description of return
*/
inline int left(int idx) {
return (idx << ) + ;
}
inline int right(int idx) {
return (idx << ) + ;
}
void max_heapify(vector<int>& nums, int idx) {
int largest = idx;
int l = left(idx), r = right(idx);
if (l < heap_size && nums[l] > nums[largest])
largest = l;
if (r < heap_size && nums[r] > nums[largest])
largest = r;
if (largest != idx) {
swap(nums[idx], nums[largest]);
max_heapify(nums, largest);
}
}
void build_max_heap(vector<int>& nums) {
heap_size = nums.size();
for (int i = (heap_size >> ) - ; i >= ; i--)
max_heapify(nums, i);
}
int kthLargestElement(int k, vector<int> nums) {
// write your code here
build_max_heap(nums);
for (int i = ; i < k; i++) {
swap(nums[], nums[heap_size - ]);
heap_size--;
max_heapify(nums, );
}
return nums[heap_size];
}
private:
int heap_size;
};

最新文章

  1. 【备忘】Conky配置
  2. Web 服务器 low bandth DOS attack
  3. npm install socket.io遇到的问题
  4. Cocos2d-x 3.0 Json用法 Cocos2d-x xml解析
  5. 【leetcode】Largest Number ★
  6. 玩转Docker镜像
  7. Android Studio的一些快捷键
  8. Android working with Volley
  9. fifo manage
  10. POJ 3174 Alignment of the Planets (暴力求解)
  11. vim的列编辑操作
  12. java.lang.NoClassDefFoundError: javax/transaction/Synchronization (jUnit测试报错)
  13. hdu 5248 序列变换(二分枚举)
  14. PMP和PRINCE2的价值各是什么?PRINCE2的含金量如何?PMP和prince2有什么区别?
  15. tomcat 下部署单框架cas时,报出org.apache.jasper.JasperException异常的解决办法
  16. Ultimus BPM 房地产与建筑行业应用解决方案
  17. Entity Framework : The model backing the &#39;&#39; context has changed since the database was created
  18. 数据标准化/归一化normalization
  19. Github 开源项目(一)websocketd (实战:实时监控服务器内存信息)
  20. git更新提交代码常用命令

热门文章

  1. JBOSS 中oracle-ds.xml的配置模板
  2. php中的重载以及几个常用的魔术方法示例
  3. hbase 批量插入api
  4. NoSQL(三)
  5. [css]margin-top重叠
  6. iOS7 SDK新特性
  7. C# 执行多条SQL更新语句,实现数据库事务
  8. 使用Lua的扩展库LuaSocket用例
  9. [转]JS脚本抢腾讯云学生1元代金券
  10. Tuning 12 manage statistics