class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
if (nums.size() == 1)
{
return nums;
}
//Count
unordered_map<int, int> cnts;
for (auto num: nums) {
cnts[num]++;
}
//Push into buckets
vector<vector<int>> bucket(nums.size() + 1);
for (auto cnt : cnts) {
bucket[cnt.second].push_back(cnt.first);
}
//Push the higher index into res
vector<int> res;
int index = 0;
for (int i = bucket.size() - 1 ; i >= 0; i--) {
if (bucket[i].size() != 0 && index < k)
{
for (auto v: bucket[i]) {
index++;
res.push_back(v);
}
}
}
return res;
}
};