Advertisement
K_S_

Untitled

Nov 1st, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1. // Runtime: 8 ms, faster than 62.46% of Java online submissions for Top K Frequent Words.
  2. // Memory Usage: 38.6 MB, less than 67.86% 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 TreeMap<>();
  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.                 return o2.count - o1.count;
  22.             }
  23.         });
  24.  
  25.         List<Pair> pairs = values.subList(0, k);
  26.         ArrayList<String> result = new ArrayList<>();
  27.         for (Pair pair : pairs) {
  28.             result.add(pair.word);
  29.         }
  30.         return result;
  31.     }
  32.  
  33.     static class Pair {
  34.         String word;
  35.         int count;
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement