Two Sum II - Input array is sorted
LeetCode: Two Sum II - Input array is sorted
Problem:
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.
- Examples:
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
- Analysis:
From problem description, the input array is sorted.
We can use two pointers to find the target tow elements whose sum is the target.
Let left = 0, right = len(arr) - 1,and sum = arr[left] + arr[right],
1. left++, if sum < target
2. right--, if sum > target
3. find, if sum = target
- Code - Java:
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int len = numbers.length;
int[] result = new int[2];
int left = 0;
int right = len - 1;
while (left < right) {
int sum = numbers[left] + numbers[right];
if (sum == target) {
result[0] = left + 1;
result[1] = right + 1;
break;
} else if (sum > target) {
do {
right--;
} while (right >= 0 && numbers[right + 1] == numbers[right]);
} else {
do {
left++;
} while (left < len && numbers[left - 1] == numbers[left]);
}
}
return result;
}
}
- Code - C++:
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int len = numbers.size();
vector<int> result(2, 0);
int left = 0;
int right = len - 1;
while (left < right) {
int sum = numbers[left] + numbers[right];
if (sum == target) {
result[0] = left + 1;
result[1] = right + 1;
break;
} else if (sum > target) {
do {
right--;
} while (right >= 0 && numbers[right + 1] == numbers[right]);
} else {
do {
left++;
} while (left < len && numbers[left - 1] == numbers[left]);
}
}
return result;
}
};
- Code - Python:
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
numberLen = len(numbers)
result = [0, 0]
left, right = 0, numberLen - 1
while left < right:
val = numbers[left] + numbers[right]
if val == target:
result[0] = left + 1
result[1] = right + 1
break
elif val > target:
right -= 1
while (right >= 0 and numbers[right + 1] == numbers[right]):
right -= 1
else:
left += 1
while (left < numberLen and numbers[left - 1] == numbers[left]):
left += 1
return result
Time Complexity: O(N), N is the length of input array
Space Complexity: O(1)