Leetcode 347 Solution
This article provides solution to leetcode question 347 (top-k-frequent-elements)
Access this page by simply typing in "lcs 347" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/top-k-frequent-elements
Solution
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
map<int, int> a;
multimap<int, int> b;
for (int i = 0; i < nums.size(); i++)
a[nums[i]]++;
for (auto it = a.begin(); it != a.end(); it++)
b.insert(make_pair(it->second, it->first));
vector<int> res;
int j = 0;
for (auto it = b.rbegin(); it != b.rend(); it++)
{
if (j < k)
res.push_back(it->second);
else
break;
j++;
}
return res;
}
};