File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time Complexity: O(n)
2+ // Space Complexity: O(m)
3+
4+ var topKFrequent = function ( nums , k ) {
5+ const frequencyMap = new Map ( ) ;
6+ // for each number in the array, update frequency.
7+ for ( const num of nums ) {
8+ frequencyMap . set ( num , ( frequencyMap . get ( num ) || 0 ) ) ;
9+ }
10+
11+ // create buckets where index represents frequency.
12+ const buckets = Array ( nums . length + 1 ) . fill ( ) . map ( ( ) => [ ] ) ;
13+ // place each number into the bucket corresponding to frequency.
14+ for ( const [ num , frequency ] of frequencyMap . entries ( ) ) {
15+ buckets [ frequency ] . push ( num ) ;
16+ }
17+
18+ const result = [ ] ;
19+ // iterate from the highest possible frequency down to the lowest.
20+ for ( let i = buckets . length - 1 ; i >= 0 && result . length < k ; i -- ) {
21+ if ( buckets [ i ] . length > 0 ) {
22+ result . push ( ...buckets [ i ] ) ;
23+ }
24+ }
25+
26+ // ensure the result length is k.
27+ return result . slice ( 0 , k ) ;
28+ } ;
You can’t perform that action at this time.
0 commit comments