───✱*.。:。✱*.:。✧*.。✰*.:。✧*.。:。*.。✱ ───
Problem
- Given an array of integers
numbersthat is sorted in non-decreasing order. - Return the indices (1-indexed) of two numbers,
[index1, index2], such that they add up to a given target numbertargetandindex1 < index2. Note thatindex1andindex2cannot be equal, therefore you may not use the same element twice. - There will always be exactly one valid solution.
- Your solution must use additional space.
Solution
- This is a pretty obvious two pointer problem, mainly since we know the array is sorted
- We can get a sum of the numbers at the left and right pointers
- If the sum is same as the target, we return the indices
[r + 1, l + 1] - If the sum is greater than the target, we decrement the right pointer
- If the sum is less than the target, we increment the left pointer
- If the sum is same as the target, we return the indices
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
# time complexity: O(n)
# space complexity: O(1)
l, r = 0, len(numbers) - 1
while l < r:
current = numbers[l] + numbers[r]
if current == target:
return [l + 1, r + 1]
elif current > target:
r -= 1
elif current < target:
l += 1───✱*.。:。✱*.:。✧*.。✰*.:。✧*.。:。*.。✱ ───