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.

假設有一個非空的整數數組,從中得到前k個出現頻率最多的數字。面試

思路和代碼

這裏有一個額外要求即時間複雜度要優於O(n log n),也就是說咱們沒法採用先排序再順序計算的方式來進行統計,由於最好的排序算法其平均的時間複雜度也須要O(n log n)。那麼有沒有別的方法能夠讓咱們達到更好的效率呢?算法

這裏的核心思路是桶排序,咱們經過使用n+1個桶(其中第i個桶表明出現i次的數據)來匯攏每一個數字出現的次數。先用HashMap來統計出現次數,而後將其丟到對應的桶中,最後從最高的桶開始向低的桶逐個遍歷,取出前k個頻率的數字。數組

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>();
            }
            buckets[frequencyOfKey].add(key);
        }
        
        List<Integer> result = new ArrayList<Integer>();
        for(int i = buckets.length-1 ; i>=0 && k>result.size() ; i--){
            if(buckets[i] != null){
                result.addAll(buckets[i]);
            }
        }
        return result;
    }

clipboard.png
想要了解更多開發技術,面試教程以及互聯網公司內推,歡迎關注個人微信公衆號!將會不按期的發放福利哦~微信

相關文章
相關標籤/搜索