给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
示例:
输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
解题思路:
- 首先 从 下标0开始,然后从1开始遍历,如果值是目标值,则输出对应的下标。
假设输入inputs的数组为长度为n。
时间复杂度 n + (n-1) + (n-1) + (n-2)+…+2+2+1 = n2 - 1 = o(n2)
空间复杂度 o(n2) - 首先 从 下标0开始,然后用目标值减去下标值1的 得到需要的值,然后在后面连接里面查 出 结果返回索引值。
假设输入inputs的数组为长度为n。
时间复杂度 (n -1 ) log n + (n-2)log (n - 1) + (n-3)log(n - 2) + … + log(2) = o(nlog n)
空间复杂度o(1) - 使用双指针,一个指针指向值较小的元素,一个指针指向值较大的元素。指向较小元素的指针从头向尾遍历,指向较大元素的指针从尾向头遍历。
假设输入inputs的数组为长度为n。
时间复杂度 n = o(n)
空间复杂度o(1)
public class TwoNumberSumSortInput {
@Test
public void twoSumTest() {
int[] ints = twoSum(new int[]{2, 7, 11, 15}, 9);
Assert.assertEquals(2, ints.length);
Assert.assertEquals(1, ints[0]);
Assert.assertEquals(2, ints[1]);
}
public int[] twoSum(int[] numbers, int target) {
int i = 0, j = numbers.length - 1;
while (i < j) {
int sum = numbers[i] + numbers[j];
if (sum == target) {
return new int[]{i + 1, j + 1};
} else if (sum < target) {
i++;
} else {
j--;
}
}
return null;
}
}