Fork me on GitHub

[leetcode-347-Top K Frequent Elements]

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].

Note: 

  • You may assume k is always valid, 1 ? k ? number of unique elements.
  • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

思路:

首先用map统计数字出现的次数,然后再将出现的次数作为关键词,使用桶排序,然后从后遍历,返回关键字即可。

复制代码
vector<int> topKFrequent(vector<int>& nums, int k)
     {
         if (nums.empty())return{};
         map<int, int>mp;
         vector<vector<int>>bucket(nums.size() + 1);
         for (auto a:nums)mp[a]++;
         for (auto it : mp)bucket[it.second].push_back(it.first);
         vector<int>ret;
         for (int i = nums.size(); i >= 0 && k>0;i--)
         {
             if (!bucket[i].empty())
             {
                 for (int j = 0; j < bucket[i].size() && k>0; j++)
                 {
                     ret.push_back(bucket[i][j]);
                     k--;
                 }
             }
         }
          
         return ret;
     }
复制代码

后来又看到有人用优先队列存储,感觉更方便了。

复制代码
 vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int,int> map;
        for(int num : nums){
            map[num]++;
        }
        
        vector<int> res;
        // pair<first, second>: first is frequency,  second is number
        priority_queue<pair<int,int>> pq; 
        for(auto it = map.begin(); it != map.end(); it++){
            pq.push(make_pair(it->second, it->first));
            if(pq.size() > (int)map.size() - k){
                res.push_back(pq.top().second);
                pq.pop();
            }
        }
        return res;
    }
复制代码

参考:

https://discuss.leetcode.com/topic/44226/c-o-n-log-n-k-unordered_map-and-priority_queue-maxheap-solution

 

posted @   hellowOOOrld  阅读(202)  评论(0编辑  收藏  举报
编辑推荐:
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
阅读排行:
· C# 13 中的新增功能实操
· Ollama本地部署大模型总结
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(4)
· langchain0.3教程:从0到1打造一个智能聊天机器人
· 2025成都.NET开发者Connect圆满结束
点击右上角即可分享
微信分享提示