思路:在递增数组中找出满足相加之和等于目标数
定义左右两个指针(下标)从数组两边开始遍历,若左右指针所指数字之和大于目标数,则将右指针自减,若左右指针所指数字之和小于目标数,则左指针自加,若左右指针所指数字之和等于目标数,则返回一个数组[++left,++right]
当左指针 >= 右指针时遍历结束,return null表示没找到
Java实现:
class Solution {public int[] twoSum(int[] numbers, int target) {int left = 0;int right = numbers.length - 1;while(left < right){if(numbers[left] + numbers[right] == target){return new int []{++left,++right};}if(numbers[left] + numbers[right] > target){right--;}if(numbers[left] + numbers[right] < target){left++;}}return null;}
}