输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。
双指针
public static int[] twoSum(int[] nums, int target) {
int i = 0 , j = nums.length - 1;
int _target = target;
int value = 0;
//找到合适的右开端
while(nums[j] > target) j--;
while (i < j){
value = _target - nums[j];
if(value < nums[i]){
j--;
}else if(value == nums[i]){
break;
}else {
i++;
}
}
return new int[]{nums[i] , nums[j]};
}
题解:https://leetcode-cn.com/problems/he-wei-sde-liang-ge-shu-zi-lcof/solution/