Top K Frequent Words
给一个字符串数组, 找到k个出现最多次数的words.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Solution { public List<String> topKFrequent(String[] words, int k) { List<String> res = new ArrayList<>(); Map<String, Integer> m = new HashMap<>(); for(String w : words) { m.putIfAbsent(w, 0); m.put(w, m.get(w) + 1); } PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>((a, b)-> (b.getValue() == a.getValue() ? a.getKey().compareTo(b.getKey()):b.getValue() - a.getValue())); for(Map.Entry<String, Integer> e : m.entrySet()) { pq.add(e); } for(int i = 0; i < k; i++) { res.add(pq.poll().getKey()); } return res; } } |