347. Top K Frequent Elements [leetcode]
来源:互联网 发布:c语言多进程编程实例 编辑:程序博客网 时间:2024/06/03 23:06
法 一:
hashmap + vector
时间:O(n)
class Solution {public: vector<int> topKFrequent(vector<int>& nums, int k) { vector<int> res; if (k < 1) return res; if (k >= nums.size()) return nums; vector<vector<int>> count(nums.size() + 1, vector<int>()); unordered_map<int, int> countList; for (auto i : nums) countList[i]++; for (unordered_map<int, int>::iterator it = countList.begin(); it != countList.end(); it++) count[it->second].push_back(it->first); for (int i = nums.size(); i >= 1 && k > 0; i--) { if (!count[i].empty()) { for (auto j : count[i]) { res.push_back(j); k--; } } } return res; }};
法二:
hashmap + priority_queue
时间:O(nlongn)
class Solution {public: vector<int> topKFrequent(vector<int>& nums, int k) { vector<int> res; if (k < 1) return res; if (k >= nums.size()) return nums; unordered_map<int, int> countList; for (auto i : nums) countList[i]++; priority_queue<pair<int,int>> q; int n = 1; for (unordered_map<int, int>::iterator it = countList.begin(); it != countList.end(); it++, n++) { q.push(make_pair(it->second, it->first)); if (n > countList.size() - k) { res.push_back(q.top().second); q.pop() ; } } return res; }};
阅读全文
0 0
- LeetCode #347. Top K Frequent Elements
- [leetcode] 347. Top K Frequent Elements
- LeetCode 347. Top K Frequent Elements
- <LeetCode OJ> 347. Top K Frequent Elements
- LeetCode 347. Top K Frequent Elements
- Leetcode 347. Top K Frequent Elements
- LeetCode Everyday: 347. Top K Frequent Elements
- 【leetcode】347. Top K Frequent Elements
- leetcode 347.Top K Frequent Elements
- leetcode 347. Top K Frequent Elements
- leetcode 347. Top K Frequent Elements
- [leetcode]347. Top K Frequent Elements
- LeetCode-347.Top K Frequent Elements
- Leetcode 347.Top K Frequent Elements
- Leetcode 347. Top K Frequent Elements
- 【LeetCode】347. Top K Frequent Elements
- [leetcode] 347. Top K Frequent Elements
- leetcode-java-347. Top K Frequent Elements
- set+ vector的详解及用法
- KVM网络性能调优终极版
- 常用的JQuery单击操作汇总
- hdu 1162 Eddy's picture 基础最小生成树★
- JS函数(一)
- 347. Top K Frequent Elements [leetcode]
- 如何提取mathematica方程的解,并用在后面的计算中
- Spring学习笔记: Repository实现(一)
- pip安装报错:is not a supported wheel on this platform
- 关于spring配置文件<context:property-placeholder>
- tocker笔记
- 双向 LSTM
- 剑指offer--二叉树的深度--层次遍历/BFS
- Centos 6 L*2tp 配置实例