Easy Java Solution


  • 0
    A

    Using Priority Queue and HashMap. Save the elements in priority queue with decreasing frequency of occurrence, and in increasing alphabetical order if the number of occurrences is same. Return the first "k" elements from the queue.

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

Log in to reply
 

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