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+ // 1. 가장 간단한 방법 이중 for문 (Runtime: 175ms / Memory: 55.8MB)
2+ // function twoSum(nums: number[], target: number): number[] {
3+ // const length = nums.length;
4+ // for (let i = 0; i < length; i++) {
5+ // for (let j = 0; j < length; j++) {
6+ // if (i === j) continue;
7+ // if (nums[i] + nums[j] === target) return [i, j]
8+ // }
9+ // }
10+ // return [];
11+ // };
12+
13+ // 2. 시간 복잡도 개선 (Runtime: 9ms / Memory: 60.4MB)
14+ function twoSum ( nums : number [ ] , target : number ) : number [ ] {
15+ const numObj = { } ;
16+ nums . forEach ( ( num , index ) => { numObj [ num ] ? numObj [ num ] . push ( index ) : numObj [ num ] = [ index ] } ) ;
17+ for ( let i = 0 ; i < nums . length ; i ++ ) {
18+ const num = target - nums [ i ] ;
19+ if ( numObj [ num ] ?. length === 1 ) {
20+ if ( i === numObj [ num ] [ 0 ] ) continue ;
21+ return [ i , numObj [ num ] [ 0 ] ] ;
22+ }
23+ else if ( numObj [ num ] ?. length === 2 ) {
24+ return numObj [ num ] ;
25+ }
26+ }
27+ return [ ] ;
28+ } ;
You can’t perform that action at this time.
0 commit comments