File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-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
+
4
+ // declare hashmap
5
+ // key: each element, value: appered count
6
+ Map <Integer , Integer > map = new HashMap <>();
7
+
8
+ // if map contains the element, increase its value by one.
9
+ // else put the element and 1 for initializing
10
+ for (int num : nums ) {
11
+ if (map .containsKey (num )) {
12
+ map .put (num , map .getOrDefault (num , 0 ) + 1 );
13
+ } else {
14
+ map .put (num , 1 );
15
+ }
16
+ }
17
+
18
+ // keyList only has key values of the hashmap
19
+ // using their value count sort keys by descending order
20
+ List <Integer > keyList = new ArrayList <>(map .keySet ());
21
+ Collections .sort (keyList , (o1 , o2 ) -> map .get (o2 ).compareTo (map .get (o1 )));
22
+
23
+
24
+ int [] output = new int [k ];
25
+ int idx = 0 ;
26
+
27
+ // retreive keys k times and set output
28
+ while (idx < k ) output [idx ] = keyList .get (idx ++);
29
+
30
+ return output ;
31
+ }
32
+ }
You can’t perform that action at this time.
0 commit comments