采用桶排序的思想
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
map<int, int> m; // 数字:次数
map<int, vector<int>, greater<int>> countMap; // 次数:[数字]
vector<int> v;
for (int i = 0; i < nums.size(); ++i) {
++m[nums[i]];
}
for ( map<int, int>::iterator iter = m.begin(); iter != m.end(); ++iter) {
if (countMap.find(iter->second) != countMap.end()) {
countMap[iter->second].push_back(iter->first);
} else {
countMap[iter->second] = vector<int>{iter->first};
}
}
for (map<int, vector<int>, greater<int>>::iterator iter = countMap.begin();
iter != countMap.end(); ++iter) {
if (v.size() + iter->second.size() <= k) {
v.insert(v.end(), iter->second.begin(), iter->second.end());
} else {
v.insert(v.end(), iter->second.begin(), iter->second.begin() + k - v.size());
}
}
return v;
}
};