Java: PriorityQueue implementation


  • 1
    E
    public class Solution {
        private class Node implements Comparable<Node> {
            private int val;
            private int freq;
    
            public Node(int val, int freq) {
                this.val = val;
                this.freq = freq;
            }
    
            public int compareTo(Node that) {
                return this.freq - that.freq;
            }
        }
        
        public List<Integer> topKFrequent(int[] nums, int k) {
            Map<Integer, Integer> map = new HashMap<>();
            for (int i : nums) {
                if (!map.containsKey(i)) map.put(i, 1);
                else map.put(i, map.get(i) + 1);
            }
            PriorityQueue<Node> pq = new PriorityQueue<>();
            for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                pq.add(new Node(entry.getKey(), entry.getValue()));
                if (pq.size() > k) pq.poll();
            }
            List<Integer> result = new ArrayList<>();
            while (!pq.isEmpty()) result.add(pq.poll().val);
            return result;
        } 
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.