方法一:排序
官方的方法,一堆没见过的方法
class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> count = new HashMap();
for (String word: words) {
count.put(word, count.getOrDefault(word, 0) + 1);
}
List<String> candidates = new ArrayList(count.keySet());
Collections.sort(candidates, (w1, w2) -> count.get(w1).equals(count.get(w2)) ?
w1.compareTo(w2) : count.get(w2) - count.get(w1));
return candidates.subList(0, k);
}
}
方法二:堆
自定义比较策略,然后Java的内部优先级队列按照这个策略建立小顶堆
就是先自定义比较策略,
1.即如果两个出现频次相同,就按字母顺序排序,比如正常来说:"i"是小于"love"的,但是题目要求i在love之前,那么比较策略就是w2.compareTo(w1),而不是正常的w1.compareTo(w2)
2.如果频次不相同,就直接比较频次,频次低的放在前边即可,就是正常的自定义比较策略count.get(w1) - count.get(w2),即然后建立小根堆
class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> count = new HashMap();
for (String word: words) {
count.put(word, count.getOrDefault(word, 0) + 1);
}
PriorityQueue<String> minHeap = new PriorityQueue<String>(
(w1, w2) -> count.get(w1).equals(count.get(w2)) ?
w2.compareTo(w1) : count.get(w1) - count.get(w2) );
for (String word: count.keySet()) {
minHeap.offer(word);
if (minHeap.size() > k) minHeap.poll();
}
List<String> ans = new ArrayList();
while (!minHeap.isEmpty()) ans.add(minHeap.poll());
Collections.reverse(ans);
return ans;
}
}