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.
这类问题主要考到了hash表的使用,使用STL来解决比较方便。可以用map来记录词频,由于map不能sort,所以还需将map转换成pair然后排序,代码如下:
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> res;
vector<pair<int,int>> pp;
for(auto t:nums)res[t]++;
for(auto r:res)pp.push_back(r);
sort(pp.begin(),pp.end(),[=](pair<int,int>&a,pair<int,int>&b){return a.second>b.second;});
vector<int> ans;
for(int i = 0;i<k;i++)ans.push_back(pp[i].first);
return ans;
}
};