Вот полный текст статьи с сайта LeetCode на английском языке:
Two Sum II - Input array is sorted
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 twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
Approach 1: Two Pointers
Algorithm
The simplest way of solving this problem is using the two pointers. We can keep two pointers i and j, representing the current indices from the beginning and the end. We then check the sum of elements at these indices.
Here is what the algorithm looks like:
- Initialize two pointers i and j pointing to the first and the last indices of the input array
- Loop while i ≤ j
- Compute the sum of elements at indices i and j.
- If the sum is equal to the target, we have found the desired sum.
- Otherwise, if the sum is less than the target, we move i one step to the right.
- Otherwise, if the sum is greater than the target, we move j one step to the left.
- Repeat steps 3-6 until the sum is equal to the target or i > j.
Steps 2-7 of the algorithm have to be repeated until the sum of elements at the current indices is equal to the target sum. When sum > target, we should move the right pointer j to the left, and when sum < target, we should move the left pointer i to the right. As a result, the pointers will eventually meet if there are any two elements in the array that add up to the target sum.
We use the fact that the input array is sorted in ascending order to avoid looking at all pairs of elements. Given two indices i and j such that i < j and the sum of elements at these indices is less than the target, we do not need to consider pairs with index i. Instead, we can consider pairs of indices (i + 1, j), (i + 2, j), and so on. Similarly, if the sum of elements at indices i and j is greater than the target, we do not need to consider pairs of indices (i, j - 1), (i, j - 2), and so on.
Time Complexity: O(n). We traverse the entire array at most once in the worst case.
Space Complexity: O(1). We only use constant extra space.
Here is the code of the two-pointers algorithm in Python:
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
i, j = 0, len(numbers) - 1
while i < j:
sum = numbers[i] + numbers[j]
if sum == target:
return [i + 1, j + 1]
elif sum < target:
i += 1
else:
j -= 1
return [-1, -1]