Top K Frequent Elements

来源:互联网 发布:网络推广代理公司 编辑:程序博客网 时间:2024/04/30 18:58

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 logn), where n is the array's size.

思路:用hashmap统计一下频率,然后用priorityqueue sort k个元素,然后取出k个元素,时间复杂度:nlgk.

注意一点,初始化priorityqueue的时候,给定的k只是给定初始值大小,限定空间大小而已,一直往里面加,size会自动增加,跟arraylist一样。所以代码中要进行poll操作,把多余k个元素自动poll出来;

public class Solution {    public class Node{        private int value ;        private int frequency;        Node(int value, int frequency){            this.value = value;            this.frequency = frequency;        }    }    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++){            if(hashmap.containsKey(nums[i])){                hashmap.put(nums[i], hashmap.get(nums[i])+1);            } else {                hashmap.put(nums[i],1);            }        }                PriorityQueue<Node> queue = new PriorityQueue<Node>(k, new myComparator());        for(Integer key: hashmap.keySet()){            Node node = new Node(key, hashmap.get(key));            queue.add(node);            if(queue.size()>k){                queue.poll();            }        }        while(queue.size()>0){            Node node = queue.poll();            list.add(node.value);        }        return list;    }        public class myComparator implements Comparator<Node> {        @Override        public int compare (Node a, Node b) {            if(a.frequency < b.frequency){                return -1;            } else if(a.frequency == b.frequency ){                return 0;            } else {                return 1;            }        }    }}




0 0
原创粉丝点击