# 前 K 个高频元素

给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。

 

示例 1:

输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]

示例 2:

输入: nums = [1], k = 1
输出: [1]

 

提示:

 

进阶:你所设计算法的时间复杂度 必须 优于 O(n log n) ,其中 n 是数组大小。

以下错误的选项是?

## aop ### before ```cpp #include using namespace std; ``` ### after ```cpp int main() { Solution sol; vector nums = {1, 1, 1, 2, 2, 3}; int k = 2; vector res; res = sol.topKFrequent(nums, k); for (auto i : res) cout << i << " "; return 0; } ``` ## 答案 ```cpp class Solution { public: vector topKFrequent(vector &nums, int k) { sort(nums.begin(), nums.end()); vector> cnt; for (int i = 0; i < nums.size();) { int count = 1; while (i + count < nums.size()) count++; cnt.push_back({nums[i], count}); i += count; } sort(cnt.begin(), cnt.end(), cmp); vector ans(k); for (int i = 0; i < k; i++) ans[i] = cnt[i].first; return ans; } }; ``` ## 选项 ### A ```cpp class Solution { public: vector topKFrequent(vector &nums, int k) { unordered_map freq; for (int i = 0; i < nums.size(); i++) { freq[nums[i]]++; } priority_queue, vector>, greater>> pq; for (auto a : freq) { if (pq.size() == k) { if (a.second > pq.top().first) { pq.pop(); pq.push(make_pair(a.second, a.first)); } } else { pq.push(make_pair(a.second, a.first)); } } vector res; while (!pq.empty()) { res.push_back(pq.top().second); pq.pop(); } return res; } }; ``` ### B ```cpp class Solution { public: static bool cmp(const vector &a, const vector &b) { return a[1] > b[1]; } vector topKFrequent(vector &nums, int k) { vector a; map list1; for (int i = 0; i < nums.size(); i++) { if (!list1.count(nums[i])) { list1.insert(map::value_type(nums[i], 1)); a.push_back(nums[i]); } else { list1[nums[i]]++; } } vector> b(a.size(), vector(2)); for (int i = 0; i < a.size(); i++) { b[i][0] = a[i]; b[i][1] = list1[a[i]]; } sort(b.begin(), b.end(), cmp); a.clear(); for (int i = 0; i < k; i++) { a.push_back(b[i][0]); } return a; } }; ``` ### C ```cpp class Solution { public: vector topKFrequent(vector &nums, int k) { unordered_map nums_count; for (auto x : nums) { nums_count[x]++; } multimap> big_m; for (auto x : nums_count) { big_m.insert(make_pair(x.second, x.first)); } vector res; for (auto it = big_m.begin(); it != big_m.end() && k; it++, k--) { res.push_back(it->second); } return res; } }; ```