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

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

cpp版手撕堆

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;
    }
};
相关推荐
RTC老炮18 小时前
webrtc弱网-AcknowledgedBitrateEstimatorInterface类源码分析与算法原理
网络·算法·webrtc
Antonio91519 小时前
【图像处理】常见图像插值算法与应用
图像处理·算法·计算机视觉
夜晚中的人海19 小时前
【C++】使用双指针算法习题
开发语言·c++·算法
im_AMBER21 小时前
数据结构 06 线性结构
数据结构·学习·算法
earthzhang20211 天前
【1028】字符菱形
c语言·开发语言·数据结构·c++·算法·青少年编程
papership1 天前
【入门级-算法-3、基础算法:二分法】
数据结构·算法
通信小呆呆1 天前
收发分离多基地雷达椭圆联合定位:原理、算法与误差分析
算法·目标检测·信息与通信·信号处理
丁浩6661 天前
Python机器学习---2.算法:逻辑回归
python·算法·机器学习
伏小白白白1 天前
【论文精度-2】求解车辆路径问题的神经组合优化算法:综合展望(Yubin Xiao,2025)
人工智能·算法·机器学习
无敌最俊朗@1 天前
数组-力扣hot56-合并区间
数据结构·算法·leetcode