Skip to content

Commit f7bf00a

Browse files
donghyeon95donghyeon95
authored andcommitted
feat: Top K Frequent Elements DaleStudy#237
1 parent fa9d506 commit f7bf00a

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import java.util.ArrayList;
2+
import java.util.Collections;
3+
import java.util.HashMap;
4+
import java.util.List;
5+
import java.util.Map;
6+
7+
class Solution {
8+
public int[] topKFrequent(int[] nums, int k) {
9+
HashMap<Integer, Integer> hm = new HashMap<>();
10+
11+
for (int num: nums) {
12+
hm.put(num, hm.getOrDefault(num, 0)+1);
13+
}
14+
15+
List<Map.Entry<Integer, Integer>> list = new ArrayList<>(hm.entrySet());
16+
list.sort(Map.Entry.comparingByValue(Collections.reverseOrder()));
17+
18+
int index = 1;
19+
ArrayList<Integer> answer = new ArrayList<>();
20+
for (Map.Entry<Integer, Integer> entry: list) {
21+
if (index > k) break;
22+
answer.add(entry.getKey());
23+
index++;
24+
}
25+
26+
return answer.stream().mapToInt(Integer::intValue).toArray();
27+
}
28+
}
29+

0 commit comments

Comments
 (0)