第一次解也是循环枚举的思想,只是因为数组有序,那么在两数相加已经大于target的情况下,以这个数字左右首元素的情况,不会再出现相加等于target的情况,所以提前结束循环
public int[] twoSum(int[] numbers, int target) {
if (numbers == null || numbers.length <= 1){
return null;
}
int [] num = new int[2];
int slow = 0;
while (slow < numbers.length){
for (int fast = slow + 1; fast < numbers.length; fast ++){
int value = numbers[slow] + numbers[fast];
if (value == target){
num[0] = slow + 1;
num[1] = fast + 1;
return num;
}
if (value > target){
break;
}
}
slow ++;
}
return null;
}
从剩下的有序数组中找一个特定的值,二分法显然会比顺序遍历快的多
ps 二分法都忘记了,需要注意边界条件
public int[] twoSum(int[] numbers, int target) {
if (numbers == null || numbers.length <= 1){
return null;
}
int [] num = new int[2];
for (int i = 0; i < numbers.length; i++){
int low = i + 1;
int high = numbers.length - 1;
int value = target - numbers[i];
while (low <= high){
int mid = (high - low)/2 + low;
if (numbers[mid] == value){
num[0] = i + 1;
num[1] = mid + 1;
return num;
}else if (numbers[mid] > value){
high = mid - 1;
}else{
low = mid + 1;
}
}
}
return null;
}
因为数组是有序的,所以可以使用快慢指针来解题,如果两数相加比target小,那么说明前面的数与剩下所有数相加都比target小,因为剩下的数都比当前后一个数小,反过来如果加起来比target大也成立
public int[] twoSum(int[] numbers, int target) {
if (numbers == null || numbers.length <= 1){
return null;
}
int [] num = new int[2];
int slow = 0;
int fast = numbers.length - 1;
while (slow != fast){
int value = numbers[slow] + numbers[fast];
if (value == target){
num[0] = slow + 1;
num[1] = fast + 1;
return num;
}else if (value > target){
fast--;
}else {
slow ++;
}
}
return null;
}