11# idea: For each number n in nums, check if (target - n) exists in the remaining elements.
22
3+ # Ans 1
34class Solution :
45 def twoSum (self , nums : List [int ], target : int ) -> List [int ]:
56 for idx , num in enumerate (nums ):
@@ -8,27 +9,28 @@ def twoSum(self, nums: List[int], target: int) -> List[int]:
89 return [idx , nums .index (required_num , idx + 1 )]
910
1011
11- '''
12- Trial and error
13- idea : two pointer
14- I struggled to handle the indices of the original array after sorting it.
15- The code below fails when negative numbers are involved.
16- I realized it would be tricky to solve this problem with the two-pointer.
17- '''
1812
19- # class Solution:
20- # def twoSum(self, nums: List[int], target: int) -> List[int]:
21- # sorted_nums = sorted(nums)
22- # left, right = 0, len(nums) - 1
13+ # Ans 2
14+ # idea : Two-pointer
15+ # Time Complexity : O(n log n)
16+
17+ class Solution :
18+ def twoSum (self , nums : List [int ], target : int ) -> List [int ]:
19+ # Keep original indices !
20+ new_nums = [(idx , num ) for idx , num in enumerate (nums )]
21+ new_nums .sort (key = lambda x : x [1 ])
22+
23+ left , right = 0 , len (new_nums )- 1
2324
24- # while left < right:
25- # s = sorted_nums[left] + sorted_nums[right]
26- # if s == target:
27- # left_idx = nums.index(sorted_nums[left])
28- # right_idx = nums.index(sorted_nums[right], left_idx + 1)
29- # return [left_idx, right_idx]
30- # elif s < target:
31- # left += 1
32- # else:
33- # right -= 1
25+ while left < right :
26+ idx_left , idx_right = new_nums [left ][0 ], new_nums [right ][0 ]
27+ val = new_nums [left ][1 ] + new_nums [right ][1 ]
28+ if val == target :
29+ return [idx_left , idx_right ]
30+ elif val < target :
31+ left += 1
32+ else :
33+ right -= 1
34+ return []
35+
3436
0 commit comments