您的位置:首页 > 其它

Week 8算法分析作业

2017-12-22 11:27 417 查看

Week 8算法分析作业

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

我的解法

使用vector存放需要的数据,建立频率和数字之间的映射,复杂度为O(NlogN)

class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> map;
for(int num : nums){
map[num]++;
}
vector<int> res;
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;
}
};


感想:

这道题感觉思路很清晰,但是操作起来很麻烦,容易乱
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: