Max Heap


  • 0
    F
     public List<String> topKFrequent(String[] words, int k) {
        
        Map<String, Integer> map = new HashMap<>();
       
        for (String word : words) {
            map.put(word, map.getOrDefault(word, 0) + 1 );
        }
    
        PriorityQueue<Map.Entry<String, Integer>> queue = new PriorityQueue<>(
            (a, b) -> a.getValue() == b.getValue() ? a.getKey().compareTo(b.getKey()) : b.getValue() - a.getValue());
        
        for(Map.Entry<String, Integer> entry : map.entrySet()) {
            queue.offer(entry);
        }
        
        List<String> res = new ArrayList<>();
        while(!queue.isEmpty() && rs.size() < k) res.add(queue.poll().getKey());
        return rs; 
    }

Log in to reply
 

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