Skip to content

Latest commit

 

History

History
66 lines (55 loc) · 2.23 KB

347.md

File metadata and controls

66 lines (55 loc) · 2.23 KB

LeetCode 347 Top K Frequent Elements——medium

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.

1

思路:
3种方法:桶排序(bucket sort)、最大堆(MaxHeap)、TreeMap

1、先讲一下堆排序:// use maxHeap. Put entry into maxHeap so we can always poll a number with largest frequency
Map提供了一些常用方法,如keySet()、Values()、entrySet()等方法,keySet()方法返回值是Map中key值的集合;Values()方法返回值是Map中Value值的集合;entrySet()的返回值也是返回一个Set集合,此集合的类型为Map.Entry。
Map.Entry是Map声明的一个内部接口,此接口为泛型,定义为Entry<K,V>。它表示Map中的一个实体(一个key-value对)。接口中有getKey(),getValue方法。
空间复杂度:O(n)
时间复杂度:O(nlogn)

2

bucket sort:桶排序:// use an array to save numbers into different bucket whose index is the frequency

3

3、// use treeMap. Use freqncy as the key so we can get all freqencies in order
public class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int n: nums){
            map.put(n, map.getOrDefault(n,0)+1);
        }
        
        TreeMap<Integer, List<Integer>> freqMap = new TreeMap<>();
        for(int num : map.keySet()){
           int freq = map.get(num);
           if(!freqMap.containsKey(freq)){
               freqMap.put(freq, new LinkedList<>());
           }
           freqMap.get(freq).add(num);
        }
        
        List<Integer> res = new ArrayList<>();
        while(res.size()<k){
            Map.Entry<Integer, List<Integer>> entry = freqMap.pollLastEntry();
            res.addAll(entry.getValue());
        }
        return res;
    }
}