两数之和 II - 输入有序数组
-
给你一个下标从 1 开始的整数数组 numbers ,该数组已按 非递减顺序排列 ,请你从数组中找出满足相加之和等于目标数 target 的两个数。
-
如果设这两个数分别是 numbers[index1] 和 numbers[index2] ,则 1 <= index1 < index2 <= numbers.length 。
-
以长度为 2 的整数数组 [index1, index2] 的形式返回这两个整数的下标 index1 和 index2。
你可以假设每个输入 只对应唯一的答案 ,而且你 不可以 重复使用相同的元素。
你所设计的解决方案必须只使用常量级的额外空间。
示例 1:
输入:numbers = [2,7,11,15], target = 9
输出:[1,2]
解释:2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。返回 [1, 2] 。
解题思路
- 由于数组已按非递减顺序排列,可以使用双指针技巧来寻找两个数之和等于目标数。
- 首先将两个指针分别指向数组的开头和结尾,然后逐步向中间移动, 根据两个指针指向的数的和与目标数的大小关系来调整指针的位置。
Java实现
public class TwoSumII {
public int[] twoSum(int[] numbers, int target) {
int left = 0, 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, -1]
}
public static void main(String[] args) {
TwoSumII twoSumII = new TwoSumII();
int[] numbers1 = {2, 7, 11, 15};
int target1 = 9;
System.out.println("Test Case 1:");
System.out.println("Numbers: [2, 7, 11, 15], Target: 9");
int[] result1 = twoSumII.twoSum(numbers1, target1);
System.out.println("Indices: [" + result1[0] + ", " + result1[1] + "]"); // Expected: [1, 2]
int[] numbers2 = {2, 3, 4};
int target2 = 6;
System.out.println("\nTest Case 2:");
System.out.println("Numbers: [2, 3, 4], Target: 6");
int[] result2 = twoSumII.twoSum(numbers2, target2);
System.out.println("Indices: [" + result2[0] + ", " + result2[1] + "]"); // Expected: [1, 3]
}
}
时间空间复杂度
时间复杂度: 使用双指针遍历数组,时间复杂度为 O(n),其中 n 是数组的长度。
空间复杂度: 使用了常量级的额外空间,空间复杂度为 O(1)。