Middle-题目132:347. Top K Frequent Elements(增补4)

题目原文:
Given a non-empty array of integers, return the k most frequent elements.

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].
题目大意:
输入一个数组和数字k,求频次最高的k个数字。
分析:
用hashmap记录频次

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        //一,统计处频次
        unordered_map<int,int> mapping;
        for(int number : nums)
            mapping[number]++;
        //二,根据频次压入最大堆中 
        // pair<first, second>: first is frequency, second is number
        priority_queue<pair<int,int>> pri_que; //最大堆
        for(auto it = mapping.begin(); it != mapping.end(); it++)
            pri_que.push(make_pair(it->second, it->first));
        //三,获取结果 
        while(result.size() < k){
                result.push_back(pri_que.top().second);
                pri_que.pop();
        }
        return result;
    }
private:
    vector<int> result;
};

成绩:
36ms

你可能感兴趣的:(Middle-题目132:347. Top K Frequent Elements(增补4))