https://algo.monster/problems/top_k_frequently_mentioned_keywords
no js?
My solution to the leetcode link:
public List topKFrequent(String[] words, int k) {
List answer = new ArrayList();
Map<String, Integer> hm = new HashMap<>();
for (int i = 0; i < words.length; i++) {
String word = words[i];
if(hm.containsKey(word)) {
hm.put(word, hm.get(word) + 1);
} else {
hm.put(word, 1);
}
}
PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>((a, b) -> {
if (a.getValue() == b.getValue()) {
return a.getKey().compareTo(b.getKey());
}
return -a.getValue().compareTo(b.getValue());
});
pq.addAll(hm.entrySet());
while(!pq.isEmpty() && answer.size() < k) {
Map.Entry<String, Integer> item = pq.poll();
answer.add(item.getKey());
}
return answer;
}