File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ const topKFrequent = ( nums , k ) => {
2+ // 1: ๋ฑ์ฅ ํ์ ์ธ๊ธฐ
3+ const countMap = new Map ( ) ;
4+ for ( const num of nums ) {
5+ countMap . set ( num , ( countMap . get ( num ) ?? 0 ) + 1 ) ;
6+ }
7+
8+ // 2: ๋ฒํท ๋ฐฐ์ด ๋ง๋ค๊ธฐ
9+ // ์ธ๋ฑ์ค = ๋น๋์, ๊ฐ = ๊ทธ ๋น๋์๋ฅผ ๊ฐ์ง ์ซ์๋ค์ ๋ฐฐ์ด
10+ // ์ต๋ ๋น๋๋ nums.length์ด๋ฏ๋ก ํฌ๊ธฐ๋ฅผ nums.length + 1๋ก ์ค์
11+ const bucket = Array . from ( { length : nums . length + 1 } , ( ) => [ ] ) ;
12+
13+ for ( const [ num , freq ] of countMap . entries ( ) ) {
14+ bucket [ freq ] . push ( num ) ;
15+ }
16+
17+ // 3: ๋ค(๋์ ๋น๋)์์๋ถํฐ ํ์ํ๋ฉฐ k๊ฐ ์์ง
18+ const result = [ ] ;
19+ for ( let i = bucket . length - 1 ; i >= 0 && result . length < k ; i -- ) {
20+ for ( const num of bucket [ i ] ) {
21+ result . push ( num ) ;
22+ if ( result . length === k ) break ;
23+ }
24+ }
25+
26+ return result ;
27+ }
You canโt perform that action at this time.
0 commit comments