Skip to content

Commit 814fa1e

Browse files
committed
"top K Frequent Elements 문제"
1 parent 5d7cff7 commit 814fa1e

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import java.util.*;
2+
import java.util.stream.Collectors;
3+
4+
class Solution {
5+
public int[] topKFrequent(int[] nums, int k) {
6+
Set<Integer> unique = Arrays.stream(nums).boxed().collect(Collectors.toSet());
7+
Map<Integer, Integer> value = new HashMap<>();
8+
for (int n : unique) {
9+
int cnt = 0;
10+
for (int m : nums) {
11+
if (n == m) {
12+
cnt++;
13+
}
14+
}
15+
value.put(n, cnt);
16+
}
17+
List<Map.Entry<Integer, Integer>> sortedByValueDesc = value.entrySet()
18+
.stream()
19+
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
20+
.toList();
21+
return sortedByValueDesc.stream()
22+
.limit(k)
23+
.map(Map.Entry::getKey)
24+
.mapToInt(Integer::intValue)
25+
.toArray();
26+
}

0 commit comments

Comments
 (0)