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 个数

统计每个数出现的频率,对频率进行桶排序

C++:

 1 class Solution {
 2 public:
 3     vector<int> topKFrequent(vector<int>& nums, int k) {
 4         unordered_map<int,int> map ;
 5         for(int num : nums){
 6             map[num]++ ;
 7         }
 8         vector<vector<int> > buckets(nums.size() + 1) ;
 9         for(auto m : map){
10             buckets[m.second].push_back(m.first) ;
11         }
12         vector<int> res ;
13         for(int i = buckets.size() - 1 ; i >= 0 && res.size() < k ; i--){
14             for(int j : buckets[i]){
15                 res.push_back(j) ;
16                 if (res.size() == k)
17                     break ;
18             }
19         }
20         return res ;
21     }
22 };
原文地址:https://www.cnblogs.com/mengchunchen/p/10255383.html