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 11class Solution {
2- public int [] topKFrequent (int [] nums , int k ) {
2+ public static int [] topKFrequent (int [] nums , int k ) {
33 Map <Integer , Integer > hashMap = new HashMap <>();
44 for (int i = 0 ; i < nums .length ; i ++) {
55 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 );
117 }
128
13- List <Integer > list = hashMap .entrySet ()
14- .stream ()
9+ List <Integer > list = hashMap .entrySet ().stream ()
1510 .sorted (Map .Entry .<Integer , Integer >comparingByValue ().reversed ())
1611 .limit (k )
1712 .map (Map .Entry ::getKey )
1813 .toList ();
1914
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 ();
2418
2519 return result ;
2620 }
You can’t perform that action at this time.
0 commit comments