class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int> count; int max_freq = 1; for (const int num : nums) // count is a map. so it can do this ++count[num]; // 这个++count[num]可不能小看, 不然++放在后,max_freq就会出问题 max_freq = max(max_freq, ++count[num]); // 使用桶排序 map<int, vector<int>> buckets; // 不是不支持c++11 而是我理解过错了, 这里用的是item.second 和item.first 是可以使用的 for (const auto& kv : count) buckets[kv.second].push_back(kv.first); vector<int> ans; for (int i = max_freq; i >= 1; --i) { if (ans.size() <k) { auto it = buckets.find(i); if (it != buckets.end()) { ans.insert(ans.end(), it->second.begin(), it->second.end()); } } } return ans; } };
leetcode 347. 前K个高频元素
猜你喜欢
转载自blog.csdn.net/weixin_36149892/article/details/80263731
今日推荐
周排行