problem Description:
Given an array of integers that's already sorted in ascending order, find, numbers such, they add up to a Specific target number.
The function twosum should return indices of the numbers such that they add up to the target, where index1 must is Les S than Index2. Please note that your returned answers (both Index1 and INDEX2) is not zero-based.
You may assume this each input would has exactly one solution.
Input: numbers={2, 7, one, target=9
Output: index1=1, index2=2
Well, are you finished the Sum problem? What would happen if the input array is sorted. Well, the key was, in this case, each target would be composed of the numbers, one in the left half of the array an D The other in the right half of the array. You could need to think a while and convince yourself of the this by some examples.
Then we simply need to set double pointers, one starts from 0 and the other starts from numbers.size ()-1. If the numbers pointed by them sum to target, we is done. Otherwise, if the sum is larger than the target, we know the number in the right half are larger and we need to mo ve the right pointer to the left by 1. The case was similar if the sum is smaller.
So we could write down the following code.
1vector<int> Twosum (vector<int> &numbers,inttarget) {2 intleft =0, right = Numbers.size ()-1;3 while(Left <Right ) {4 if(Numbers[left] + numbers[right] = =target)5 return{left +1, right +1};6 if(Numbers[left] + numbers[right] >target)7right--;8 Elseleft++;9 }Ten}
[Leetcode] Both Sum ii-input array is sorted