-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopKFrequentElements.java
More file actions
29 lines (25 loc) · 900 Bytes
/
Copy pathTopKFrequentElements.java
File metadata and controls
29 lines (25 loc) · 900 Bytes
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
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Solution {
public int[] topKFrequent(int[] nums, int k) {
if (k > nums.length) {
return nums;
}
Map<Integer, Integer> frequencyMap = new HashMap<>();
for (int num : nums) {
if (frequencyMap.containsKey(num)) {
frequencyMap.put(num, frequencyMap.get(num) + 1);
}
else
frequencyMap.put(num, 1);
}
List<Integer> list = frequencyMap.entrySet().stream().sorted(Comparator.comparing(Map.Entry<Integer, Integer>::getValue).reversed()).limit(k).map(Map.Entry<Integer, Integer>::getKey).toList();
int[] result = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
}