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.
就是找出現(xiàn)頻率前K個(gè)的數(shù)。想法就是用map統(tǒng)計(jì)出次數(shù)來。然后按次數(shù)排序舞肆。輸出前K個(gè)數(shù)嫩与。
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;
}
};