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. The function should return the indices of the two numbers (1-based index).
Initialization:
pointer_1
) and one at the end (pointer_2
) of the array.Iterate and Adjust Pointers:
pointer_1
) to the right to increase the sum.pointer_2
) to the left to decrease the sum.End Condition:
class Solution(object):
def twoSum(self, numbers, target):
pointer_1 = 0
pointer_2 = len(numbers) - 1
while pointer_1 < pointer_2:
if numbers[pointer_1] + numbers[pointer_2] == target:
return [pointer_1 + 1, pointer_2 + 1]
if numbers[pointer_1] + numbers[pointer_2] < target:
pointer_1 += 1
else:
pointer_2 -= 1