File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int [] topKFrequent (int [] nums , int k ) {
3
+ //hashmap, check count == k, add to result
4
+ //List<Integer> result = new ArrayList();
5
+ HashMap <Integer , Integer > map = new HashMap ();
6
+ //int max = 0;
7
+
8
+ for (int idx =0 ;idx <nums .length ;idx ++){
9
+ int num = nums [idx ];
10
+
11
+ map .put (num , map .getOrDefault (num ,0 )+1 );
12
+
13
+ //max = Math.max(max, map.get(num));
14
+ }
15
+ List <Integer > set = new ArrayList <Integer >(map .keySet ());
16
+ List <Integer >[] out = new List [nums .length +1 ];
17
+
18
+ for (int idx =0 ;idx <set .size ();idx ++){
19
+ int count = map .get (set .get (idx ));
20
+
21
+ //if (count )
22
+ if (out [count ] == null )out [count ] = new ArrayList <Integer >();
23
+
24
+ out [count ].add (set .get (idx ));
25
+ }
26
+
27
+ int [] result = new int [k ];
28
+ int i =0 ;
29
+ for (int idx =out .length -1 ;i <k ;idx --) {
30
+ if (out [idx ] == null ) continue ;
31
+
32
+ for (Integer temp : out [idx ]){
33
+ if (i >=k ) break ;
34
+
35
+ result [i ++]= temp ;
36
+ }
37
+ }
38
+ return result ;
39
+ }
40
+ }
You can’t perform that action at this time.
0 commit comments