File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ // 2차: index를 값으로 갖는 Map을 활용하여 한번의 순회로 답안 도출
2
+ // TC: O(N)
3
+ // SC: O(N)
4
+
5
+ /**
6
+ * @param {number[] } nums
7
+ * @param {number } target
8
+ * @return {number[] }
9
+ */
10
+ var twoSum = function ( nums , target ) {
11
+ const valueIndexMap = new Map ( ) ;
12
+
13
+ for ( let index = 0 ; index < nums . length ; index ++ ) {
14
+ const value = nums [ index ] ;
15
+ const anotherValue = target - value ;
16
+
17
+ if ( valueIndexMap . has ( anotherValue ) ) {
18
+ return [ index , valueIndexMap . get ( anotherValue ) ] ;
19
+ }
20
+
21
+ valueIndexMap . set ( value , index ) ;
22
+ }
23
+ } ;
24
+
25
+ // 1차: 정렬 후 투포인터 활용
26
+ // TC: O(N * logN)
27
+ // SC: O(N)
28
+
29
+ /**
30
+ * @param {number[] } nums
31
+ * @param {number } target
32
+ * @return {number[] }
33
+ */
34
+ var twoSum = function ( nums , target ) {
35
+ const sortedNums = nums
36
+ . map ( ( value , index ) => ( { value, index } ) )
37
+ . sort ( ( a , b ) => a . value - b . value ) ;
38
+ let left = 0 ;
39
+ let right = sortedNums . length - 1 ;
40
+
41
+ while ( left < right ) {
42
+ const sum = sortedNums [ left ] . value + sortedNums [ right ] . value ;
43
+ if ( sum < target ) {
44
+ left += 1 ;
45
+ } else if ( sum > target ) {
46
+ right -= 1 ;
47
+ } else {
48
+ return [ sortedNums [ left ] . index , sortedNums [ right ] . index ] ;
49
+ }
50
+ }
51
+ } ;
You can’t perform that action at this time.
0 commit comments