Given a 1-indexed array of integers
Return the indices of the two numbers,
The tests are generated such that there is exactly one solution. You may not use the same element twice.
Your solution must use only constant extra space.
Example 1
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
Example 2
Output: [1,3]
Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].
Example 3
Output: [1,2]
Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].
Constraints:
-
2 <= numbers.length <= 3 * 104 -
-1000 <= numbers[i] <= 1000 -
numbers is sorted in non-decreasing order. -
-1000 <= target <= 1000 - The tests are generated such that there is exactly one solution.
Contents
Solution 1 - Using Two pointers
Since the input array
Implementation steps:
-
Create two variables
left andright , to point to left and right ends of the input arraynumbers . Initialize them withleft = 0 andright = nums.length -1 . -
Then, loop through elements of
numbers using awhile loop untilleft andright don't intersect with each other, compute the sum of elements atleft andright indexes, and check the following:- If sum is equal to target: Then return the indexes (add +1 to the indexes, since the input array is 1-indexed).
-
If sum is less than target: Then increment
left index by 1, since the sum is less than target. -
If sum is greater than target: Then decrement
right index by 1, since the sum is greater than target.
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(1).
Above implementations source code can be found at