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; } };
感想:
这道题感觉思路很清晰,但是操作起来很麻烦,容易乱相关文章推荐
- Week 13算法分析作业
- Week 18算法分析作业
- Week 6算法分析作业
- Week 10算法分析作业
- Week 14算法分析作业
- Week 12算法分析作业
- Week 16算法分析作业
- Week 15算法分析作业
- Week 17算法分析作业
- Week 3算法分析作业
- Week 4算法分析作业
- Week 9算法分析作业
- Week 2算法分析作业
- (算法分析Week2)Two Sum[Easy]
- 【算法设计作业】week3
- 计算机算法设计与分析作业01:分治法求解大数乘法+L型骨牌的棋盘覆盖问题
- Week 1 Analysis of Algorithm(算法分析)
- 算法分析与设计课程作业第十四周#1#2#3
- 个人作业Week3-案例分析
- 算法分析与设计课程作业第十周#1