本题 题目链接
题目描述

我的题解
双指针

思路分析
- 因为该数组是递增数组,所以我们可以用双指针法。
- 声明指针left 和 right分别指向数组的头(数组下标为0)和尾(数组下标为length-1)
- 循环搜索:当两指针相遇时,结束循环
- 计算nums[left]和nums[right]的和 s
- 若s = target,直接 返回nums[left]和nums[right];
- 若s > target,right指针向左移动:right-- ;
- 若s < target,left指针向右移动:left++ ;
- 若找不到符合题目要求的两个数,返回空数组
代码如下
public int[] twoSum(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left < right) {
int s = nums[left] + nums[right];
if (s == target) return new int[]{nums[left], nums[right]};
else if (s > target) right--;
else left++;
}
return new int[0];
}
补充:关于数据溢出问题【我上面代码就不改了哈】

