0%

Top K Frequent Words

Question

Given a non-empty list of words, return the k most frequent elements.

Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

Example 1:
Input: [“i”, “love”, “leetcode”, “i”, “love”, “coding”], k = 2
Output: [“i”, “love”]
Explanation: “i” and “love” are the two most frequent words.
Note that “i” comes before “love” due to a lower alphabetical order.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*
@param: String[] words, int k
@return: List<String>
Algorithm: 这题同https://leetcode.com/problems/top-k-frequent-elements/
*/
public List<String> topKFrequent(String[] words, int k) {
List<String> result = new ArrayList<>();
if (words.length == 0 || k > words.length) {
return result;
}

Map<String, Integer> map = new HashMap<>();

// sort condition修改一下
PriorityQueue<String> heap = new PriorityQueue<>(
(o1,o2) -> map.get(o2) == map.get(o1) ? o1.compareTo(o2) : map.get(o2) - map.get(o1));

for (int i = 0; i < words.length; i++) {
map.put(words[i], map.getOrDefault(words[i], 0)+1);
}

for (String s : map.keySet()){
heap.offer(s);
}

for (int i = 0; i < k; i++) {
result.add(heap.poll());
}
return result;
}