- 利用哈希表储存字符串及其出现次数
- 利用堆和比较器根据出现次数对字符串进行排序
- Comparator:比较器 :
s1 - s2 (升序)--------------------------: s2 - s1(降序)
s2.compareTo(s1)(a在后,升序)-: s1.compareTo(s2)(a在前:降序) - 根据输出字符的个数K,从堆中取顶并依次删除K个至ArrayList集合中
- 返回集合,结束
下面展示一些 内联代码片
。
package Heap;
import java.util.*;
public class test3 {
public static void main(String[] args) {
String[] words = {"i", "love", "leetcode", "i", "love", "coding"};
int k = 2;
topKFrequent(words, k);
}
public static void topKFrequent(String[] words, int k) {
//利用哈希表统计字符串及其个数
Hashtable<String,Integer> map = new Hashtable<>();
for (int i = 0 ; i < words.length; i++ ) {
if (!map.containsKey(words[i])) {
map.put(words[i], 0);
} else {
int count = map.get(words[i]) + 1;
map.put(words[i], count);
}
}
//利用比较器进行键(次数)的比较,再对字符进行比较
PriorityQueue<String> heap = new PriorityQueue<String>(new Comparator<String>(){
@Override
public int compare(String s1, String s2) {
int num = map.get(s2) - map.get(s1);
int num1 = num == 0? s1.compareTo(s2) : num;
return num1;
}
});
//将字符串存入堆内
for (String key : map.keySet()){
heap.add(key);
}
//存放输出元素集合
ArrayList<String> arr = new ArrayList<>();
//获取堆顶元素并删除更新堆顶元素
while(k > 0){
String peek = heap.peek();
arr.add(peek);
heap.poll();
k--;
}
System.out.println(arr);
}
}