c++
class element {
public:
element() {}
element(int a, int b) : key(a), cnt(b) {}
int key;
int cnt;
inline bool operator<(const element &x) const { return cnt > x.cnt; }
};
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
if (nums.empty()) return vector<int>();
unordered_map<int, int> cache;
for (auto &v : nums) {
cache[v]++;
}
multiset<element> dict;
for (auto &v : cache) {
dict.insert(element(v.first, v.second));
}
vector<int> res;
int i = 0;
for (auto &v : dict) {
if (i++ == k) break;
res.push_back(v.key);
}
return res;
}
};
python
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
cache = collections.defaultdict(int)
for v in nums:
cache[v] += 1
cache = sorted(cache.items(), key=lambda d: d[1]) [::-1]
return [x[0] for x in itertools.islice(cache, k)]