forked from algorithm024/algorithm024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopKFrequent_347.java
More file actions
78 lines (76 loc) · 2.38 KB
/
Copy pathTopKFrequent_347.java
File metadata and controls
78 lines (76 loc) · 2.38 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
public class TopKFrequent_347 {
/**
* 最小堆解法:1、用字典统计每个元素出现的频率
* 2、定义比较器用PirorityQueue维护一个k个元素的最小堆
* 3、将最小堆的元素输出
* @param nums
* @param k
* @return
*/
public int[] topKFrequent1(int[] nums, int k) {
//用字典统计数组中每个元素出现的频率
Map<Integer, Integer> map = new HashMap<>();
for(int num : nums) {
if(map.containsKey(num)) {
map.put(num, map.get(num) + 1);
}else{
map.put(num, 1);
}
}
//用pirorityqueue维护一个只有k个元素的最小堆
PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>(){
@Override
public int compare(Integer a, Integer b) {
return map.get(a) - map.get(b);
}
});
for(int key : map.keySet()) {
if(queue.size() < k) {
queue.add(key);
}else if(map.get(key) > map.get(queue.peek())){
queue.poll();
queue.add(key);
}
}
int[] result = new int[k];
for(int i = 0; i < k; i++) {
result[i] = queue.poll();
}
return result;
}
/**
* 使用大根堆的方式求解
* @param nums
* @param k
* @return
*/
public int[] topKFrequent2(int[] nums, int k) {
int[] result = new int[k];
// 先用map统计数组中每个元素出现的频次
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
if (map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
// 定义一个大根堆
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> {
return map.get(b) - map.get(a);
});
// 将map的keyset依次加入queue
for (Integer key : map.keySet()) {
maxHeap.add(key);
}
// 取出大根堆的前k个元素
for (int i = 0; i < k; i++) {
result[i] = maxHeap.poll();
}
return result;
}
}