167 Two Sum II - Input array is sorted

1. Question

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 haveexactlyone solution and you may not use thesameelement twice.
Input:numbers={2, 7, 11, 15}, target=9 Output:index1=1, index2=2

2. Implementation

(1) Two Pointers
1
class Solution {
2
public int[] twoSum(int[] numbers, int target) {
3
int start = 0, end = numbers.length - 1;
4
int sum = 0;
5
6
int[] res = new int[2];
7
8
while (start < end) {
9
sum = numbers[start] + numbers[end];
10
11
if (sum == target) {
12
res[0] = start + 1;
13
res[1] = end + 1;
14
break;
15
}
16
else if (sum < target) {
17
++start;
18
}
19
else {
20
--end;
21
}
22
}
23
return res;
24
}
25
}
Copied!
(2) Two Pointers
1
class Solution {
2
public int[] twoSum(int[] numbers, int target) {
3
if (numbers == null || numbers.length == 0) {
4
return new int[2];
5
}
6
7
int[] res = new int[2];
8
9
for (int i = 0; i < numbers.length; i++) {
10
int index = binarySearch(numbers, i + 1, target - numbers[i]);
11
12
if (index != -1) {
13
res[0] = i + 1;
14
res[1] = index + 1;
15
break;
16
}
17
}
18
return res;
19
}
20
21
public int binarySearch(int[] numbers, int start, int target) {
22
int end = numbers.length - 1, mid = 0;
23
24
while (start <= end) {
25
mid = start + (end - start) / 2;
26
27
if (numbers[mid] == target) {
28
return mid;
29
}
30
else if (numbers[mid] < target) {
31
start = mid + 1;
32
}
33
else {
34
end = mid - 1;
35
}
36
}
37
return -1;
38
}
39
}
Copied!

3. Time & Space Complexity

Two Pointers:时间复杂度O(n), 空间复杂度O(1)
Binary Search: 时间复杂度O(logn), 空间复杂度O(1)