Skip to content

Commit e714695

Browse files
committed
347. Top K Frequent Elements
Aug 12
1 parent 4002eb2 commit e714695

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public int[] topKFrequent(int[] nums, int k) {
3+
4+
// declare hashmap
5+
// key: each element, value: appered count
6+
Map<Integer, Integer> map = new HashMap<>();
7+
8+
// if map contains the element, increase its value by one.
9+
// else put the element and 1 for initializing
10+
for (int num : nums) {
11+
if (map.containsKey(num)) {
12+
map.put(num, map.getOrDefault(num, 0) + 1);
13+
} else {
14+
map.put(num, 1);
15+
}
16+
}
17+
18+
// keyList only has key values of the hashmap
19+
// using their value count sort keys by descending order
20+
List<Integer> keyList = new ArrayList<>(map.keySet());
21+
Collections.sort(keyList, (o1, o2) -> map.get(o2).compareTo(map.get(o1)));
22+
23+
24+
int[] output = new int[k];
25+
int idx = 0;
26+
27+
// retreive keys k times and set output
28+
while (idx < k) output[idx] = keyList.get(idx++);
29+
30+
return output;
31+
}
32+
}

0 commit comments

Comments
 (0)