当前位置: 首页 > news >正文

力扣hot100——347.前K个高频元素(cpp手撕堆)

题目链接:347. 前 K 个高频元素 - 力扣(LeetCode)

cpp版手撕堆

class Solution {
public:// 向下调整堆(最小堆)void shiftDown(vector<pair<int, int>>& heap, int index,int len) {int parent = index;int child = 2 * parent + 1;while (child < len) {if (child + 1 < len && heap[child + 1].second < heap[child].second) {child++;}if (heap[parent].second > heap[child].second) {swap(heap[parent], heap[child]);parent = child;child = 2 * parent + 1;} else {break;}}}vector<int> topKFrequent(vector<int>& nums, int k) {// 统计每个数字出现的频率unordered_map<int, int> freqMap;for (int num : nums) {freqMap[num]++;}// 初始化堆,放入前 k 个元素vector<pair<int, int>> minHeap;for (const auto& entry : freqMap) {if (minHeap.size() < k) {minHeap.push_back(entry);}}// 构造一个合法的最小堆for (int i = minHeap.size() / 2 - 1; i >= 0; i--) {shiftDown(minHeap, i,k);}// 处理剩下的元素int processedCount = 0;for (const auto& entry : freqMap) {if (processedCount < k || entry.second <= minHeap[0].second) {processedCount++;continue;}minHeap[0] = entry;shiftDown(minHeap, 0,k);}// 提取结果vector<int> result;for (const auto& p : minHeap) {result.push_back(p.first);}return result;}
};

相关文章:

  • 霍夫圆变换全面解析(OpenCV)
  • 在scala中使用sparkSQL连接MySQL并添加新数据
  • 需求跟踪矩阵准确性的5大策略
  • java使用 FreeMarker 模板生成包含图片的 `.doc` 文件
  • 《数据库原理》部分习题解析
  • MySQL——八、SQL优化
  • 精简大语言模型:用于定制语言模型的自适应知识蒸馏
  • 商业航天运动控制系统中的高可靠性芯片解决方案:挑战、策略与应用研究
  • 每周靶点分享:Nectin-4、CDH6及文献分享
  • Deno、Bun、Node.js 性能对比与选型指南
  • Linux进程信号处理(26)
  • Axure高级交互设计:文本框循环赋值实现新增、修改和查看
  • Codis集群搭建和集成使用的详细步骤示例
  • Chrome浏览器离线版安装包下载
  • TensorFlow之微分求导
  • spark-cache模式
  • Java基础 5.13
  • SQL 中 INSTR 函数简介及 截取地址应用
  • 125.在 Vue3 中使用 OpenLayers 实现通过 WebGLVector 的方式添加海量点
  • Deepseek+Xmind:秒速生成思维导图与流程图
  • 广东省中医院脾胃病科大科主任张北平病逝,年仅52岁
  • 京东一季度净利增长五成,营收增速创近三年新高,称外卖业务取得显著进展
  • 中国巴西民间推动建立经第三方验证的“森林友好型”牛肉供应链
  • 乌方:泽连斯基只接受与普京会谈,拒见其他俄代表
  • 中央结算公司:减免境外央行类机构账户开户费用
  • 水豚“豆包”出逃已40天,扬州茱萸湾景区追加悬赏