[LintCode] 第k大元素
基于快速排序:
1 class Solution { 2 public: 3 /* 4 * param k : description of k 5 * param nums : description of array and index 0 ~ n-1 6 * return: description of return 7 */ 8 int kthLargestElement(int k, vector<int> nums) { 9 // write your code here 10 int left = 0, right = nums.size() - 1; 11 while (true) { 12 int pos = partition(nums, left, right); 13 if (pos == k - 1) return nums[pos]; 14 if (pos < k - 1) left = pos + 1; 15 if (pos > k - 1) right = pos - 1; 16 } 17 } 18 private: 19 int partition(vector<int>& nums, int left, int right) { 20 int pivot = nums[left]; 21 int l = left + 1, r = right; 22 while (l <= r) { 23 if (nums[l] < pivot && nums[r] > pivot) 24 swap(nums[l++], nums[r--]); 25 if (nums[l] >= pivot) l++; 26 if (nums[r] <= pivot) r--; 27 } 28 swap(nums[left], nums[r]); 29 return r; 30 } 31 };
基于最大堆:
1 class Solution { 2 public: 3 /* 4 * param k : description of k 5 * param nums : description of array and index 0 ~ n-1 6 * return: description of return 7 */ 8 inline int left(int idx) { 9 return (idx << 1) + 1; 10 } 11 inline int right(int idx) { 12 return (idx << 1) + 2; 13 } 14 void max_heapify(vector<int>& nums, int idx) { 15 int largest = idx; 16 int l = left(idx), r = right(idx); 17 if (l < heap_size && nums[l] > nums[largest]) 18 largest = l; 19 if (r < heap_size && nums[r] > nums[largest]) 20 largest = r; 21 if (largest != idx) { 22 swap(nums[idx], nums[largest]); 23 max_heapify(nums, largest); 24 } 25 } 26 void build_max_heap(vector<int>& nums) { 27 heap_size = nums.size(); 28 for (int i = (heap_size >> 1) - 1; i >= 0; i--) 29 max_heapify(nums, i); 30 } 31 int kthLargestElement(int k, vector<int> nums) { 32 // write your code here 33 build_max_heap(nums); 34 for (int i = 0; i < k; i++) { 35 swap(nums[0], nums[heap_size - 1]); 36 heap_size--; 37 max_heapify(nums, 0); 38 } 39 return nums[heap_size]; 40 } 41 private: 42 int heap_size; 43 };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· “你见过凌晨四点的洛杉矶吗?”--《我们为什么要睡觉》
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· C# 从零开始使用Layui.Wpf库开发WPF客户端
· C#/.NET/.NET Core技术前沿周刊 | 第 31 期(2025年3.17-3.23)
· 接口重试的7种常用方案!