leetcode : 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

 

难度: medium

tag : hashmap   heap sort (data structure: priority queue)

 

步骤:

1. 一次遍历,用户hashmap存储出现的数及对应的次数

2. 写一个PriorityQueue比较Map.Entry

3. 把top k Map.Entry入列

4. 把top k Map.Entry.getKey() 放入ArrayList 中

 

public class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
        
        //1.  iterator all the distinct elements and count
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i = 0; i < nums.length; i++) {
            if(!map.containsKey(nums[i])) {
                map.put(nums[i], 1);
            } else {
                map.put(nums[i], map.get(nums[i]) + 1);
            }
        }
        
        //2. heap sort 
        PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<Map.Entry<Integer, Integer>>(
            new Comparator<Map.Entry<Integer, Integer>>(){
                public int compare(Map.Entry<Integer, Integer> entry1, Map.Entry<Integer, Integer> entry2) {
                    return entry1.getValue() - entry2.getValue();
                }
            });
            
        //3. top K entry
        for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if(queue.size() < k) {
                queue.offer(entry);
            } else if(queue.peek().getValue() < entry.getValue()) {
                queue.poll();
                queue.offer(entry);
            }
        }
        
        //4. top k entry.key 
        
        List<Integer> answer = new ArrayList<Integer>();
        for(Map.Entry<Integer, Integer> entry : queue) {
            answer.add(entry.getKey());
        }
        
        return answer;
        
    }
}

 

posted @ 2017-04-19 11:39  notesbuddy  阅读(153)  评论(0编辑  收藏  举报