Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Write a function twoSum
to find the two numbers such that they add up to the target, and return their indices (1-indexed).
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore, the indices of 2 and 7 are returned as [1,2].
The problem can be solved by using the Two Pointers approach.
left
and right
, pointing to the first and last elements of the array, respectively.left
is less than right
.left
and right
.
left
and right
(1-indexed).left
by 1 to move towards larger numbers.right
by 1 to move towards smaller numbers.Here is the implementation of the twoSum
function in Python:
def twoSum(numbers, target):
left = 0
right = len(numbers) - 1
while left < right:
sum = numbers[left] + numbers[right]
if sum == target:
return [left+1, right+1]
elif sum < target:
left += 1
else:
right -= 1
return [] # No solution found
This implementation has a time complexity of O(n), where n is the length of the input array.