leetcode-347、前K个高频元素

https://leetcode-cn.com/problems/top-k-frequent-elements/

思路:priority_queue和unordered_map使用

struct cmp {
    bool operator() (pair<int, int> a, pair<int, int> b) {
        return a.second < b.second;
    }
};

vector<int> topKFrequent(vector<int>& nums, int k) {
    priority_queue<pair<int, int>, vector<pair<int, int> >, cmp> pri_q;
    unordered_map<int, int> un_mp;
    vector<int> res;
    for (int i = 0;i < nums.size(); i++) {
        un_mp[nums[i]] += 1;
    }
    for (unordered_map<int, int>::iterator it = un_mp.begin() ;it != un_mp.end() ; it++) {
        pri_q.push(make_pair(it->first, it->second));
    }
    int j = 0;
    while (!pri_q.empty() && j < k) {
        j += 1;
        res.push_back(pri_q.top().first);
        pri_q.pop();
    }
    return res;

}

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页