Advertisement
K_S_

Untitled

Nov 1st, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.26 KB | None | 0 0
  1. // Runtime: 6 ms, faster than 96.26% of Java online submissions for Top K Frequent Words.
  2. // Memory Usage: 38.5 MB, less than 73.21% of Java online submissions for Top K Frequent Words.
  3.  
  4. class Solution {
  5.     public List<String> topKFrequent(String[] words, int k) {
  6.         Map<String, Pair> countMap = new HashMap<>();
  7.         for (String word : words) {
  8.             Pair pair = countMap.get(word);
  9.             if (pair == null) {
  10.                 pair = new Pair();
  11.                 pair.word = word;
  12.             }
  13.             pair.count++;
  14.             countMap.put(word, pair);
  15.         }
  16.  
  17.         List<Pair> values = new ArrayList<>(countMap.values());
  18.         values.sort(new Comparator<Pair>() {
  19.             @Override
  20.             public int compare(Pair o1, Pair o2) {
  21.                 int i = o2.count - o1.count;
  22.                 if(i == 0) {
  23.                     return o1.word.compareTo(o2.word);
  24.                 }
  25.                 return i;
  26.             }
  27.         });
  28.  
  29.         List<Pair> pairs = values.subList(0, k);
  30.         ArrayList<String> result = new ArrayList<>();
  31.         for (Pair pair : pairs) {
  32.             result.add(pair.word);
  33.         }
  34.         return result;
  35.     }
  36.  
  37.     static class Pair {
  38.         String word;
  39.         int count;
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement