【算法】【c++】【堆】347. Top K Frequent Elements

堆的典型例题
Given a non-empty array of integers, return the k most frequent elements.

class Solution {
public:
    static bool comp(pair<int, int> a, pair<int, int> b){
        return a.second > b.second; //小顶堆要大于号
    }
    vector<int> topKFrequent(vector<int>& nums, int k) {
        //要选出前k大的元素 就是建立一个小顶堆
        //在遍历的过程中剩下的就是要求的
        //先把元素求出来
        unordered_map<int, int> mp;
        for(auto n: nums) {
            mp[n]++;
        }
        priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(&comp)> q(comp);
        for(auto& p: mp){
            if(q.size() >= k){
                //判断是否替换堆顶
                if(p.second > q.top().second) {
                    q.pop();
                    q.push(p);
                }
            }else{
                //直接放入
                q.push(p);
            }
        }
        vector<int> res;
        while(!q.empty()){
            res.push_back(q.top().first);
            q.pop(); //queue不能随机存取
        }
        return res;
    }
};

简简单单试验一下堆

#include<bits/stdc++.h>

using namespace std;

bool cmp(int& a, int& b) {
    if(a < b) {
        return true;
    }
    return false;
}

int main() {
    priority_queue<int, vector<int>, decltype(&cmp)> q(cmp);
    for(int i = 0; i < 5; ++i) {
        q.push(20 - i);
    }
    int temp;
    while (!q.empty())
    {
        temp = q.top();
        q.pop();
        cout << temp << endl;
    }
    return 0;    
}
  1. 最接近原点的 K 个点
    排序和堆两种方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值