167. Two Sum II - Input array is sorted
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2
双指针,一个在左,一个在右,通过判断当前指向数字之和与target的关系,移动左指针或右指针。
时间复杂度:O(n)
空间复杂度:O(1)
class Solution {
public int[] twoSum(int[] numbers, int target) {
int length = numbers.length;
if(length == 0 || length == 1)
return null;
int start = 0;
int end = length - 1;
while(start < end){
int tempSum = numbers[start] + numbers[end];
if(tempSum == target){
return new int[]{start + 1,end + 1};
}else if(tempSum > target){
end--;
}else{
start++;
}
}
return null;
}
}