美文网首页Leetcode
Leetcode.347.Top K Frequent Elem

Leetcode.347.Top K Frequent Elem

作者: Jimmy木 | 来源:发表于2019-12-31 17:03 被阅读0次

    题目

    给定一个数组,输出出现频率最多的K个数。

    Input: nums = [1,1,1,2,2,3], k = 2
    Output: [1,2]
    Input: nums = [1], k = 1
    Output: [1]
    

    思路

    先用map计算每个数的出现频率,将map转化为数组进行倒序排序,取出k个数。

    vector<int> topKFrequent(vector<int>& nums, int k) {
        vector<int> res;
        if (nums.empty()) return res;
        unordered_map<int, int> mp;
        for (auto& e : nums) mp[e]++;
    
        vector<pair<int, int>> count(mp.begin(), mp.end());
        sort(count.begin(), count.end(), [](pair<int, int> a, pair<int, int> b){return a.second > b.second;});
        for (int i = 0; i < k; i++) {
            res.push_back(count[i].first);
        }
    
        return res;
    }
    

    总结

    熟练掌握容器的各种API,熟练掌握Lambda表达式。

    相关文章

      网友评论

        本文标题:Leetcode.347.Top K Frequent Elem

        本文链接:https://www.haomeiwen.com/subject/fxqioctx.html