Skip to content

Commit 342ebab

Browse files
committed
add solution for top-k-frequent-elements
1 parent f5a2365 commit 342ebab

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import java.util.*;
2+
3+
class Solution {
4+
public int[] topKFrequent(int[] nums, int k) {
5+
HashMap<Integer, Integer> maps = new HashMap<>(); //nums[i] 대상, 등장 횟수
6+
7+
for(int i =0; i <nums.length; i++){
8+
maps.put(nums[i], maps.getOrDefault(nums[i], 0) + 1);
9+
}
10+
11+
12+
13+
ArrayList<Integer> list = new ArrayList<>();
14+
//maps를 value기준으로 내림차순 정렬후, list에 k개만큼만 key값 추가
15+
Map<Integer, Integer> sorts =
16+
maps.entrySet()
17+
.stream()
18+
.sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed())
19+
.limit(k)
20+
.collect(Collectors.toMap(
21+
Map.Entry::getKey,
22+
Map.Entry::getValue,
23+
(a, b) -> a,
24+
LinkedHashMap::new
25+
));
26+
27+
for(int t : sorts.keySet()){
28+
list.add(t);
29+
}
30+
31+
return list.stream()
32+
.mapToInt(Integer::intValue)
33+
.toArray();
34+
35+
//list.stream().mapToInt(Integer::intValue).toArray();
36+
//Arrays.stream(arr).boxed().toList();
37+
}
38+
}

0 commit comments

Comments
 (0)