-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode347.java
More file actions
66 lines (59 loc) · 1.89 KB
/
LeetCode347.java
File metadata and controls
66 lines (59 loc) · 1.89 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
import java.util.Arrays;
import java.util.HashMap;
import java.util.PriorityQueue;
public class LeetCode347 {
public static void main(String[] args) {
// 输入: nums = [1,1,1,2,2,3], k = 2
// 输出: [1,2]
System.out.println(Arrays.toString(new Solution347().topKFrequent(new int[] { 1, 1, 1, 2, 2, 3 }, 2)));
// 输入: nums = [1], k = 1
// 输出: [1]
System.out.println(Arrays.toString(new Solution347().topKFrequent(new int[] { 1 }, 1)));
}
}
class Solution347 {
private class Item implements Comparable<Item> {
int key;
int value;
public Item(int key, int value) {
this.key = key;
this.value = value;
}
public int compareTo(Item other) {
if (this.value > other.value) {
return 1;
} else if (this.value < other.value) {
return -1;
} else {
return 0;
}
}
}
public int[] topKFrequent(int[] nums, int k) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
map.put(nums[i], map.get(nums[i]) + 1);
} else {
map.put(nums[i], 1);
}
}
PriorityQueue<Item> pq = new PriorityQueue<Item>();
for (int key : map.keySet()) {
if (pq.size() < k) {
pq.add(new Item(key, map.get(key)));
} else {
if (pq.peek().value < map.get(key)) {
pq.poll();
pq.add(new Item(key, map.get(key)));
}
}
}
Object[] arr = pq.toArray();
int[] res = new int[k];
for (int i = 0; i < res.length; i++) {
res[i] = ((Item) arr[i]).key;
}
return res;
}
}