692. Top K Frequent Words
1 class Solution { 2 public List<String> topKFrequent(String[] words, int k) { 3 HashMap<String, Integer> map = new HashMap<>(); 4 List<String> res = new ArrayList<>(); 5 if(words.length == 0) return res; 6 for(String word : words){ 7 map.put(word, map.getOrDefault(word, 0) + 1); 8 } 9 List<String>[] arr = new ArrayList[words.length+1]; 10 for(String word : map.keySet()){ 11 if(arr[map.get(word)] == null){ 12 arr[map.get(word)] = new ArrayList<>(); 13 } 14 arr[map.get(word)].add(word); 15 } 16 int count = 0; 17 for(int i = arr.length - 1; i >= 0; i--){ 18 if(arr[i] != null){ 19 Collections.sort(arr[i]); 20 for(int j = 0; j < arr[i].size(); j++){ 21 if(count < k){ 22 res.add(arr[i].get(j)); 23 count++; 24 } 25 } 26 if(count == k){ 27 break; 28 } 29 } 30 } 31 return res; 32 33 } 34 }