# leetcode347. Top K Frequent Elements

## 题目要求

```Given a non-empty array of integers, return the k most frequent elements.

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].

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.```

## 思路和代码

```    public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer>[] buckets = new List[nums.length + 1];
Map<Integer, Integer> frequency = new HashMap<Integer, Integer>();

for(int num : nums){
frequency.put(num, frequency.getOrDefault(num, 0) + 1);
}

for(int key : frequency.keySet()){
int frequencyOfKey = frequency.get(key);
if(buckets[frequencyOfKey] == null){
buckets[frequencyOfKey] = new ArrayList<Integer>();
}
}

List<Integer> result = new ArrayList<Integer>();
for(int i = buckets.length-1 ; i>=0 && k>result.size() ; i--){
if(buckets[i] != null){
}
}
return result;
}```

71 篇文章13 人订阅

0 条评论

## 相关文章

### [LeetCode] 40. Combination Sum II

【原题】 Given a collection of candidate numbers (C) and a target number (T), fi...

1955

911

711

### HashMap的实现原理

HashMap是基于哈希表的Map接口的非同步实现。此实现提供所有可选的映射操作，并允许使用null值和null键。此类不保证映射的顺序，特别是它不保证该顺序恒...

2592

22810

1050

23810

3424

2123

3759