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.
Subscribe to see which companies asked this question
class Solution {
public:
static bool cmp(map<int,int>::iterator a,map<int,int>::iterator b)
{
return (a->second)>(b->second);
}
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int> v1;
map<int,int> m1;
vector<map<int,int>::iterator> temp;
for(int i=0;i<nums.size();++i)
{
m1[nums[i]]++;
}
for(auto p=m1.begin();p!=m1.end();++p)
{
temp.push_back(p);
}
sort(temp.begin(),temp.end(),cmp);
for(int i=0;i<k;++i)
{
v1.push_back(temp[i]->first);
}
return v1;
}
};