Top-k test

 

 

public class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
        //1.  遍历独立的元素并计数
        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. 堆排序
        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 @ 2019-03-13 15:03  notesbuddy  阅读(132)  评论(0编辑  收藏  举报