Top K Frequent Words

给一个字符串数组, 找到k个出现最多次数的words.

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;
    }
}