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.
就是找出现频率前K个的数。想法就是用map统计出次数来。然后按次数排序。输出前K个数。
struct CmpByValue {
bool operator()(const pair<int, int>& l, const pair<int, int>& r) {
return l.second > r.second;
}
};
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
map<int,int> table;
for(int i = 0; i < nums.size(); i++)
{
table[nums[i]]++ ;
}
vector<pair<int, int> >tableVec(table.begin(), table.end());
sort(tableVec.begin(), tableVec.end(), CmpByValue());
vector<int> res;
for(int i = 0; i<k; i++)
res.push_back(tableVec[i].first);
return res;
}
};
网友评论