Top K Frequent Elements

来源:互联网 发布:淘宝卖家破损补寄 编辑:程序博客网 时间:2024/05/16 15:01

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.
思路:求 Top K 问题,一般都是用 min heap, 如果后进来的元素比当前peek的元素要大,则pop heap ,然后加入最新的元素,这样最后的heap就是保留了最大的k个值。

public class Solution {    class Node{        int fre;        int val;        public Node( int val, int fre){            this.val = val;            this.fre = fre;        }    }        public List<Integer> topKFrequent(int[] nums, int k) {        List<Integer> list = new ArrayList<Integer>();        HashMap<Integer, Integer> hashmap = new HashMap<Integer, Integer>();        for(int i=0; i<nums.length; i++){            Integer num = hashmap.get(nums[i]);            if(num == null){                hashmap.put(nums[i], 1);            } else {                hashmap.put(nums[i], num+1);            }        }                PriorityQueue<Node> pq = new PriorityQueue<Node>(k, new Comparator<Node>(){            @Override            public int compare(Node a, Node b){                return a.fre - b.fre;            }        });        for(Integer key : hashmap.keySet()){            int fre = hashmap.get(key);            if(pq.size()>=k){                if(fre > pq.peek().fre){                    pq.poll();                    pq.add(new Node(key.intValue(), fre));                }            } else {                 pq.add(new Node(key.intValue(), fre));            }        }        while(pq.size()>0){            list.add(0,pq.poll().val);        }        return list;    }}


0 0
原创粉丝点击