Advertisement
exmkg

Untitled

Oct 27th, 2024
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.25 KB | None | 0 0
  1. class Solution {
  2.     public List<String> topKFrequent(String[] words, int k) {
  3.         List<String> result = new LinkedList<>();
  4.        
  5.         Map<String, Integer> map = new HashMap<>();
  6.         for (int i = 0; i < words.length; i++) {
  7.             if (map.containsKey(words[i])) {
  8.                 map.put(words[i], map.get(words[i]) + 1);
  9.             } else {
  10.                 map.put(words[i], 1);
  11.             }
  12.         }
  13.          
  14.         PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>(
  15.             (a, b) -> (a.getValue() == b.getValue() ? // if frequencies are equal
  16.                        b.getKey().compareTo(a.getKey()) : // put lexicographically larger first
  17.                        a.getValue() - b.getValue()) // otherwise, least frequent to the front
  18.         );
  19.        
  20.         for (Map.Entry<String, Integer> entry: map.entrySet()) {
  21.             pq.offer(entry);
  22.             if (pq.size() == k + 1) { // if priority queue size got to k+1
  23.                 // Remove least frequent and lexicographically largest string to leave only k
  24.                 pq.poll();
  25.             }
  26.         }
  27.  
  28.         while (!pq.isEmpty()) {
  29.             result.add(0, pq.poll().getKey());
  30.         }
  31.        
  32.         return result;
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement