[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; }
参考:
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· C# 13 中的新增功能实操
· Ollama本地部署大模型总结
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(4)
· langchain0.3教程:从0到1打造一个智能聊天机器人
· 2025成都.NET开发者Connect圆满结束