File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 347. Top K Frequent Elements
3
+ * Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in
4
+ * any order.
5
+ * https://leetcode.com/problems/top-k-frequent-elements/description/
6
+ */
7
+ function topKFrequent ( nums : number [ ] , k : number ) : number [ ] {
8
+ const map = new Map < number , number > ( ) ;
9
+
10
+ nums . forEach ( ( n ) => {
11
+ const count = map . get ( n ) ;
12
+ if ( count ) {
13
+ map . set ( n , count + 1 ) ;
14
+ return ;
15
+ }
16
+ map . set ( n , 1 ) ;
17
+ } ) ;
18
+
19
+ const kvArray = [ ...map ] ;
20
+ const sorted = kvArray . sort ( ( [ , v1 ] , [ , v2 ] ) => v2 - v1 ) ;
21
+
22
+ const result : number [ ] = [ ] ;
23
+ for ( let i = 0 ; i < k ; i ++ ) {
24
+ result . push ( sorted [ i ] [ 0 ] ) ;
25
+ }
26
+
27
+ return result ;
28
+ }
29
+
30
+ // O(n) time
31
+ // O(n) space
You can’t perform that action at this time.
0 commit comments