# 【347】前K个高频元素
阅读量 loading
# 一、题目
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
输入:
nums = [1,1,1,2,2,3], k = 2
1
输出:
[1,2]
1
示例 2:
输入:
nums = [1], k = 1
1
输出:
[1]
1
说明:
- 你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
- 你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
# 二、题解
public class Solution {
/**
* 时间复杂度 O(nlogk)
*
* @param nums
* @param k
* @return
*/
public List<Integer> topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new TreeMap<>();
for (int num : nums) {
if (map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(Comparator.comparingInt(map::get));
for (int key : map.keySet()) {
if (priorityQueue.size() < k) {
priorityQueue.add(key);
} else if (map.get(key) > map.get(priorityQueue.peek())) {
priorityQueue.remove();
priorityQueue.add(key);
}
}
LinkedList<Integer> result = new LinkedList<>();
while (!priorityQueue.isEmpty()) {
result.add(priorityQueue.remove());
}
return result;
}
public static void main(String[] args) {
int[] nums = {1, 1, 1, 2, 2, 3};
int k = 2;
System.out.println(new Solution().topKFrequent(nums, k));
}
}
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
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
执行结果:
[2, 1]
1