692.前K个高频单词
思路1:
- 创建HashMap,并把单词以及其频率存进HashMap中
- 将keySet()存进List链表中,并用Collections的sort进行逻辑的排序
- 再创建满足题意的新链表,返回新链表即可
代码实现
class Solution {
public List<String> topKFrequent(String[] words, int k) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < words.length; i++) {
int frequency = map.getOrDefault(words[i], 0) + 1;
map.put(words[i], frequency);
}
List<String> list = new LinkedList<String>(map.keySet());
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (map.get(o1).equals(map.get(o2))) {
return o1.compareTo(o2);
} else {
return map.get(o2) - map.get(o1);
}
}
});
List<String> list2 = new LinkedList<String>();
for (int i = 0; i < k; i++) {
list2.add(list.get(i));
}
return list2;
}
}
思路2:
- 创建HashMap并存进去
- 使用优先队列,改成最大堆以及题目相应的逻辑
- 取k次堆顶即可
代码实现
class Solution {
public List<String> topKFrequent(String[] words, int k) {
HashMap<String, Integer> map = new HashMap<>();
for (String str : words) {
map.put(str, map.getOrDefault(str, 0) + 1);
}
PriorityQueue<String> queue = new PriorityQueue<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (map.get(o1).equals(map.get(o2))) {
return o1.compareTo(o2);
} else {
return map.get(o2) - map.get(o1);
}
}
});
for (String word : map.keySet()) {
queue.add(word);
}
List<String> list = new LinkedList<String>();
for (int i = 0; i < k; i++) {
list.add(queue.poll());
}
return list;
}
}