forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTonyKim9401.java
More file actions
32 lines (25 loc) · 996 Bytes
/
Copy pathTonyKim9401.java
File metadata and controls
32 lines (25 loc) · 996 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
30
31
32
class Solution {
public int[] topKFrequent(int[] nums, int k) {
// declare hashmap
// key: each element, value: appered count
Map<Integer, Integer> map = new HashMap<>();
// if map contains the element, increase its value by one.
// else put the element and 1 for initializing
for (int num : nums) {
if (map.containsKey(num)) {
map.put(num, map.getOrDefault(num, 0) + 1);
} else {
map.put(num, 1);
}
}
// keyList only has key values of the hashmap
// using their value count sort keys by descending order
List<Integer> keyList = new ArrayList<>(map.keySet());
Collections.sort(keyList, (o1, o2) -> map.get(o2).compareTo(map.get(o1)));
int[] output = new int[k];
int idx = 0;
// retreive keys k times and set output
while (idx < k) output[idx] = keyList.get(idx++);
return output;
}
}