码迷,mamicode.com
首页 > 其他好文 > 详细

347. Top K Frequent Elements

时间:2016-05-29 16:22:19      阅读:279      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/neweracoding/p/5539510.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!