Understand and use PriorityQueue

Implementation PriorityQueue

http://www.voidcn.com/blog/u012881904/article/p-5985172.html

Time complexity:

Insert (Object): O(logn)

  Add to last location, then re-shuffle

Remove (Object): O(n)

  Find the location of object to remove (O(n)), then re-shuffle (O(logn))

 

Demo:

(https://leetcode.com/problems/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

public class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
        
        HashMap<Integer, Integer> map = new HashMap();
        for (int num : nums) {
            if (map.containsKey(num)) {
                map.put(num, map.get(num)+1);
            } else {
                map.put(num, 1);
            }
        }
        
        Queue<int[]> queue = new PriorityQueue<int[]> (new Comparator<int[]>() {
            public int compare(int[] a1, int[] a2) {
                return a2[1] - a1[1];
            }
        });
        
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            queue.offer(new int[] {entry.getKey(), entry.getValue()});
        }
        
        List<Integer> res = new ArrayList();
        
        while (res.size() < k) {
            res.add(queue.poll()[0]);
        }
        
        return res;
    }
}

 

posted on 2016-10-24 10:38  kkkiii  阅读(200)  评论(0)    收藏  举报