File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments