给定升序数组,找到两个数使他们之和等于目标数
例如:
给定数组[2,4,7,9],找到两个数使他们之和等于9.
返回[1,3]。
使用“左右指针”,往中间靠拢。
代码:
public static int[] twoSum(int[] source, int target){
int left = 0;//左边指针起始位置
int right = source.length-1;//右边指针起始位置
while(left<right){
int sum = source[left]+source[right];
if(sum == target){
return new int[]{left+1,right+1};
}else if(sum>target){
right--;//左移
}else if(sum<target){
left++;//右移
}
}
return new int[]{-1,-1};
}