LeetCode:Top K Frequent Elements

Top K Frequent Elements

 
Total Accepted: 5045  Total Submissions: 11511  Difficulty: Medium

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.

Subscribe to see which companies asked this question

Hide Tags
  Hash Table Heap
Hide Similar Problems
  (M) Word Frequency (M) Kth Largest Element in an Array






















思路:桶排序

有6个数:1 1 1 2 2 3

key:0 1 2 3 4 5 6

val:0 3 2 1 0 0 0

其中:val代表key出现的频数。


根据频数大小:

key:1 2 3

val:3 2 1

其中key代表频数,val代表频数对应的数



java code:

public class Solution {  
    public List<Integer> topKFrequent(int[] nums, int k) {  

        Map<Integer,Integer> map = new HashMap<Integer,Integer>();

        int len = nums.length;  
        List<Integer>[] bucket = new List[len+1];  
          
        for(int num:nums) {  
            map.put(num, map.getOrDefault(num, 0)+1);  
        }

        for(int key:map.keySet()) {  
            int value = map.get(key);  
            if(null == bucket[value]) bucket[value] = new ArrayList<Integer>();  
              
            bucket[value].add(key);  
        }

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


你可能感兴趣的:(LeetCode,top,Frequent,K,Eleme)