题目:LCR 006
解法一:遍历所有组合
最简单方法:双循环遍历,遍历每一个组合,判断二者相加是否等于target,但是没有利用到数组有序这一特点
解法二:二分查找
先写一个循环,固定被加数a,然后通过二分查找在后面的子序列中查找target-a
class Solution {
public int[] twoSum(int[] numbers, int target) {
for (int i = 0; i < numbers.length; i++) {
int index = binarySearch(numbers, target - numbers[i], i + 1, numbers.length - 1);
if (index > 0) {
return new int[]{i, index};
}
}
return new int[]{-1, -1};
}
}
注意:二分查找仅对有序数组有效
解法三:双指针
前指针指向第一个元素,后指针指向最后一个元素,二者向中间方向靠拢
class Solution {
public int[] twoSum(int[] numbers, int target) {
int low = 0, high = numbers.length - 1;
while (low < high) {
if (numbers[low] + numbers[high] == target) {
return new int[]{low, high};
} else if (numbers[low] + numbers[high] < target) {
low++;
} else {
high--;
}
}
return new int[]{-1, -1};
}
}
注意:仅对有序数组有效