[LeetCode] Problem 167 - 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.

Note

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.

Example

Input: numbers = [2,7,11,15], target = 9

Output: [1,2]

Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

O(nlogn) runtime, O(1) space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length && nums[i] <= target; i++) {
int num = nums[i];
int j = binarySearch(nums, i + 1, nums.length - 1, target - num);

if (j != -1)
return i < j ? new int[] {i + 1, j + 1} : new int[] {j + 1, i + 1};
}

return null;
}

private int binarySearch(int[] nums, int start, int end, int target) {
while (start <= end) {
int mid = (start + end) >> 1;

if (nums[mid] < target)
start = mid + 1;
else if (nums[mid] > target)
end = mid - 1;
else
return mid;
}

return -1;
}

O(n) runtime, O(1) space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public int[] twoSum(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;

while (start < end) {
if (nums[start] + nums[end] < target)
start++;
else if (nums[start] + nums[end] > target)
end--;
else
return new int[] {start + 1, end + 1};
}

return null;
}