347. Top K Frequent Elements
题目描述:
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
解题思路:
先统计每个数据的个数,然后按出现次数进行排序,得到出现频率最高的前K个数。
在排序时需要注意要先将map中的数据保存到vector中,然后再使用sort进行排序。
代码:
1 class Solution { 2 public: 3 vector<int> topKFrequent(vector<int>& nums, int k) { 4 unordered_map<int, int> num_map; 5 for (auto num : nums) 6 num_map[num]++; 7 vector<int> ret; 8 vector<pair<int, int> >tmp; 9 ret.reserve(k); 10 tmp.reserve(num_map.size()); 11 for (auto ite = num_map.begin(); ite != num_map.end(); ++ite) { 12 tmp.push_back(make_pair(ite->first, ite->second)); 13 } 14 sort(tmp.begin(), tmp.end(), 15 [](const pair<int, int> &x, const pair<int, int> &y) -> int { 16 return x.second > y.second; 17 }); 18 for (int i = 0; i < k; ++i) { 19 ret.push_back(tmp[i].first); 20 } 21 return ret; 22 } 23 };