给定一个生序排序的整数数组 numbers,从数组中找出两个数满足相加之和等于目标数 target。
假设每个输入只对应唯一的答案,而且不可以重复使用相同的元素。
返回两数的下标值,以数组的形式返回。
二分查找法:
public static int[] twoSearch(int[] numbers, int target) {
for (int i = 0; i < numbers.length; i++) {
int low = i, high = numbers.length - 1;
while (low <= high) {
int mid = (high - low) / 2 + low;
if (numbers[mid] == target - numbers[i]) {
return new int[]{i, mid};
} else if (numbers[mid] > target - numbers[i]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
}
return new int[]{0};
}
双指针:
public static int[] twoPoint(int[] numbers, int target) {
int low = 0, high = numbers.length - 1;
while (low < high) {
int sum = numbers[low] + numbers[high];
if (sum == target) {
return new int[]{low, high};
} else if (sum < target) {
low++;
} else {
high--;
}
}
return new int[]{0};
}