347. Top K Frequent Elements

Posted 蜃利的阴影下

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了347. 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.

 

 

Subscribe to see which companies asked this question

Hide Tags
 Hash Table Heap
 
 
Use Bucket Sort:
public List<Integer> topKFrequent(int[] nums, int k) {

    List<Integer>[] bucket = new List[nums.length + 1];
    Map<Integer, Integer> frequencyMap = new HashMap<Integer, Integer>();

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

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

    List<Integer> res = new ArrayList<>();

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

 

 
 
Use Heap.
public class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
        
        HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
        
        for(int i = 0; i<nums.length; ++i)
        {
            Integer count = m.get(nums[i]);
            if(count == null)
            {
                m.put(nums[i], 1);
            }
            else
            {
                m.put(nums[i], count+1);
            }
        }
        
        
        PriorityQueue<int[]> pq = new PriorityQueue<int[]>(k, new Comparator<int[]>(){
            @Override
            public int compare(int[] a1, int[] a2)
            {
                return a1[1] - a2[1];
            }
        } );
        
        
        for(Map.Entry<Integer, Integer> entry : m.entrySet())
        {
            if(pq.size() < k)
                pq.add(new int[]{entry.getKey(), entry.getValue()});
            else if(pq.peek()[1]<entry.getValue())
            {
                pq.remove();
                pq.add(new int[]{entry.getKey(), entry.getValue()});
            }
        }
        
        LinkedList<Integer> ret = new LinkedList<Integer>();
        while(!pq.isEmpty())
        {
            ret.push(pq.remove()[0]);
        }
        return ret;
    }
}

 

 
 
 

以上是关于347. Top K Frequent Elements的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 347. Top K Frequent Elements

347. Top K Frequent Elements

347. Top K Frequent Elements

347. Top K Frequent Elements

347. Top K Frequent Elements

347. Top K Frequent Elements