Skip to content

Commit 1eee833

Browse files
committed
top k frequent solution by the hashmap
1 parent 954babb commit 1eee833

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
public class Solution {
5+
public int[] topKFrequent(int[] nums, int k) {
6+
Map<Integer, Integer> map = new HashMap<>();
7+
8+
// count how many duplicated numbers in the input array
9+
for (int num : nums) {
10+
map.put(num, map.getOrDefault(num, 0) + 1);
11+
}
12+
13+
return map.entrySet().stream().sorted((a, b) -> b.getValue() - a.getValue()).limit(k)
14+
.mapToInt(Map.Entry::getKey).toArray();
15+
}
16+
}

0 commit comments

Comments
 (0)