leetcode 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.
经典的bucket排序。
用一个bucket的array本身的序号来反应每个key的频率。比如,1出现了3次,那就把1这个元素放进bucket[3]里。
class Solution { public List<Integer> topKFrequent(int[] nums, int k) { int l = nums.length; Map<Integer, Integer> map = new HashMap<>(); List<Integer>[] bucket = new List[l+1]; for(int n: nums) { //用一行来代替if从句。 map.put(n, map.getOrDefault(n, 0) + 1); } for(int key: map.keySet()) { int f = map.get(key); if(bucket[f] == null) { bucket[f] = new ArrayList<>(); } bucket[f].add(key); } List<Integer> res = new ArrayList<>(); for(int p = bucket.length-1; p >=0 && res.size() < k; p--) { //将频率为p的所有key加入res if(bucket[p] != null) res.addAll(bucket[p]); } return res; } }
浙公网安备 33010602011771号