File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11/*
22ํ์ด
3- nums๋ฅผ ๊ฐ๊ณผ index๊ฐ ์๋ ๊ฐ์ฒด ๋ฐฐ์ด newNums๋ก ์ฌ์ ์ํ๋ค
4- newNums๋ฅผ ๊ฐ ์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌํ๊ณ ๋ ํฌ์ธํฐ start, end๋ฅผ ๋๋ค
5- nums[start] + nums[end]๊ฐ target๋ณด๋ค ์์ผ๋ฉด start+1ํ๊ณ , target๋ณด๋ค ํฌ๋ฉด end-1ํ๋ค. ๊ฐ์ผ๋ฉด nums[start]๊ณผ nums[end]์ ์ค๋ฆฌ์ง index๋ฅผ ๋ฆฌํดํ๋ค.
6- ๋ง์ฝ start>=end๊ฐ ๋๋ฉด ๋น ๋ฐฐ์ด์ ๋ฆฌํดํ๋ค
3+ ํด์๋งต์ ์ด์ฉํด ํ์ฌ ๊ฐ์ ๋ณด์(target - num)๊ฐ ์ด๋ฏธ ๋ฑ์ฅํ๋์ง ํ์ธํ๋ค.
4+
75
86์๊ฐ๋ณต์ก๋
9- O(nLogN ) - ์ ๋ ฌ. ํฌ์ธํฐ ์ํ๋ O(N)์ด๋ฏ๋ก ์ต์ข
์ ์ผ๋ก O(nLogN)
7+ O(N ) - nums ์ํ
108
119๊ณต๊ฐ๋ณต์ก๋
12- O(N) : newNums ๋ฐฐ์ด
10+ O(N) - numObj ์์ฑ
1311*/
1412
1513function twoSum ( nums : number [ ] , target : number ) : number [ ] {
16- const newNums = nums . map ( ( value , idx ) => ( { value, idx } ) )
17- const sortedNums = newNums . sort ( ( a , b ) => a . value - b . value )
18- let start = 0
19- let end = nums . length - 1
14+ const numObj : { [ key : number ] : number } = { }
2015
21- while ( start < end ) {
22- const total = sortedNums [ start ] . value + sortedNums [ end ] . value
23- if ( total === target ) {
24- return [ sortedNums [ start ] . idx , sortedNums [ end ] . idx ]
25- } else if ( total > target ) {
26- end -= 1
16+ for ( let i = 0 ; i < nums . length ; i ++ ) {
17+ const num = nums [ i ]
18+ if ( target - num in numObj ) {
19+ return [ i , numObj [ target - num ] ]
2720 } else {
28- start += 1
21+ numObj [ num ] = i
2922 }
3023 }
3124
You canโt perform that action at this time.
0 commit comments