File tree Expand file tree Collapse file tree 1 file changed +6
-12
lines changed Expand file tree Collapse file tree 1 file changed +6
-12
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
- public int [] topKFrequent (int [] nums , int k ) {
2
+ public static int [] topKFrequent (int [] nums , int k ) {
3
3
Map <Integer , Integer > hashMap = new HashMap <>();
4
4
for (int i = 0 ; i < nums .length ; i ++) {
5
5
int num = nums [i ];
6
- if (hashMap .containsKey (num )) {
7
- hashMap .put (num , hashMap .get (num ) + 1 );
8
- continue ;
9
- }
10
- hashMap .put (num , 1 );
6
+ hashMap .put (num , hashMap .getOrDefault (num , 0 ) + 1 );
11
7
}
12
8
13
- List <Integer > list = hashMap .entrySet ()
14
- .stream ()
9
+ List <Integer > list = hashMap .entrySet ().stream ()
15
10
.sorted (Map .Entry .<Integer , Integer >comparingByValue ().reversed ())
16
11
.limit (k )
17
12
.map (Map .Entry ::getKey )
18
13
.toList ();
19
14
20
- int [] result = new int [list .size ()];
21
- for (int i = 0 ; i < list .size (); i ++) {
22
- result [i ] = list .get (i );
23
- }
15
+ int [] result = list .stream ()
16
+ .mapToInt (Integer ::intValue )
17
+ .toArray ();
24
18
25
19
return result ;
26
20
}
You can’t perform that action at this time.
0 commit comments