05 August 2008
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.
Note:
Example:
1
2
3
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.
是上一道题1-2Sum的变种,按照第二种办法先排序再两个指针找的情况,因为input是sorted的数组,所以连排序都不用了,而且也不用一个额外的数组来存排序之前的indices,相比之下是更简单了。
Time:O(n),Space:O(1)。
的当然,跟上一道题一样,也可以用HashMap来解,无论输入的array是否sorted,
Time: O(n), Space: O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int[] twoSum(int[] numbers, int target) {
if (numbers == null || numbers.length <= 1) {
return new int[]{-1, -1};
}
int left = 0;
int right = numbers.length - 1;
while (left <= right) {
int sum = numbers[left] + numbers[right];
if (sum == target) {
return new int[]{left + 1, right + 1};
} else if (sum < target) {
left++;
} else {
right--;
}
}
return new int[]{-1, -1};
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
int left = 0, right = numbers.length - 1;
while (left < right) {
if (numbers[left] + numbers[right] < target) {
left++;
} else if (numbers[left] + numbers[right] > target) {
right--;
} else {
break;//遇到合适的pair直接break,省点时间,有唯一解的情况
}
}
//因为两个indices不是zero-based,所以+1,从1开始数
result[0] = left + 1;
result[1] = right + 1;
return result;
}
}