File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change
1
+ var topKFrequent = function ( nums , k ) {
2
+ // 1. count the frequency of each number in the array
3
+ const map = new Map ( ) ;
4
+
5
+ // iterating through the array to count how many times each num appears.
6
+ for ( const num of nums ) {
7
+ // if the num already exists in the map, increment its count
8
+ if ( map . has ( num ) ) {
9
+ map . set ( num , map . get ( num ) + 1 ) ;
10
+ } // otherwise, set it to 1
11
+ else map . set ( num , 1 ) ;
12
+ }
13
+
14
+ // 2.create an array to store the freqeuncy numbers
15
+ const freqArr = [ ] ;
16
+ for ( const [ num , freq ] of map ) {
17
+ freqArr . push ( [ num , freq ] ) ;
18
+ }
19
+ // sort in descending order by frequency
20
+ freqArr . sort ( ( a , b ) => b [ 1 ] - a [ 1 ] ) ;
21
+ return freqArr . slice ( 0 , k ) . map ( ( [ num ] ) => num ) ;
22
+ } ;
23
+
24
+ // Time complexity: O(nlogn)
25
+ // Space complexity: O(n)
You can’t perform that action at this time.
0 commit comments