0%

LeetCode-347

题目

结果

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Set<Integer> set = new HashSet<>();
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
set.add(num);
if (map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
var res = set.stream().sorted((num1, num2) -> Integer.compare(map.get(num2), map.get(num1))).collect(Collectors.toList());
int[] ans = new int[k];
for (int i = 0; i < ans.length; i++) {
ans[i] = res.get(i);
}
return ans;
}
}

复杂度

时间复杂度:O(nlogn)

空间复杂度:O(n)