Title Link: http://www.lintcode.com/zh-cn/problem/two-sum/
Given an array of integers, find two numbers so that they are equal to a given number of target.
Backup a copy, and then sort. Make two pointers from left to right start scanning, each time to determine the sum of the two is not in line with test instructions, if small, then the left hand pointer to the right, the same as the pointer. The location is then found in the array of backups.
1 classSolution:2 """3 @param numbers:an array of integers4 @param target:target = numbers[index1] + numbers[index2]5 @return: [index1 + 1, Index2 + 1] (Index1 < INDEX2)6 """7 deftwosum (self, Numbers, target):8 #Write your code here9TMP = []Ten forIinchnumbers: One tmp.append (i) ANumbers =sorted (Numbers) -A =0 -b = Len (numbers)-1 the whileTrue: - ifNumbers[a] + numbers[b] = =Target: - Break - elifNumbers[a] + Numbers[b] <Target: +A + = 1 - elifNumbers[a] + numbers[b] >Target: +B-= 1 AReta =Numbers[a] atRETB =Numbers[b] -A =-1 -b =-1 - forIinchRange (0, Len (tmp)): - ifTmp[i] = = Reta andA = =-1: -A =I in elifTmp[i] = = Retb andb = =-1: -b =I to ifA >B: +A = a ^b -b = a ^b theA = a ^b * return[A+1, B+1]
[Lintcode Two-sum] Two number of sum (python, double pointer)