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