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 and you may not use the same element TWIC E.
Input:numbers={2, 7, one, A, target=9
Output:index1=1, index2=2
This title describes:give us a
non-descending array and a
target value to find the
index position of two numbers in the array,
these two numbers satisfy the added value is the target value and the case guarantee must have a
unique answer . There are no multiple and no solutionsrequires that each element in the array
be used only once ! My train of thought:because the answer is unique, there will be no more than one and no more, so save a lot of steps. I look in the middle from start (initial 0) and last (final position)if the sum is greater than the target last left shiftIf the addition is less than the target start shift rightreturn to start and end when equalMy python code:
1 classsolution (object):2 deftwosum (self, Numbers, target):3 """4 : Type Numbers:list[int]5 : Type Target:int6 : Rtype:list[int]7 """8Start, end = 0, Len (numbers)-19 whileTrue:Ten ifNumbers[start] + numbers[end] >Target: OneEnd-= 1 A elifNumbers[start] + Numbers[end] <Target: -Start + = 1 - Else : the Break - return(Start+1, End+1 ) - - + if __name__=='__main__': -s =solution () +res = S.twosum ([2,3,4],6) A Print(RES)
Leetcode algorithm: Both Sum ii-input array is sorted