The subject premise is that there must be such a two number
The solution is not written ... Not surprisingly.
The first thought is the solution to the second and final hash table
(The idea is to create an array of the same size as target.) It is written to index, but to find it all, it's a two-dimensional array, but it's a waste of space when it comes to the idea that target is big. So change into dict)
Later found the topic only asked to give two numbers just fine AH--
Extension issues are more interesting
Looking for three should not be difficult, others are not clear, there are want to add ...
1. Two-dimensional array
Def Find_pair (A, target): B = [[] for I in range (target + 1)] for I in range (0, Len (A)): if a[i] <= target: b[a[i]].append (i) for I in range (0, TARGET/2 + 1): If Len (b[i])! = 0 and Len (b[target-i])! = 0: Print (I, B[i], target-i, b[target-i]) if __name__ = = "__main__": A = [0, 1, 1, 2, one, 8, 3, 4, 5, 6, 7, 8, 9, ten] Find_pair (A, 9)
2. Dictionaries
Def Find_pair (A, target): B = {} for I in range (0, Len (A)): if a[i] <= target: if not B.has_key (A[i]): C4/>b[a[i]] = [i] else: b[a[i]].append (i) for I in range (0, TARGET/2 + 1): if B.has_key (i) and B.has_key (target-i): print (i, b[i], target-i, b[target-i]) if __name__ = = "__main__": A = [0, 1, 1, 2, 11, 8, 3, 4, 5 , 6, 7, 8, 9, ten] Find_pair (A, 9)
3. This method has been re-sequenced, do not know what the book is also returned to the index has meaning ... Sort of lazy directly with the built-in ...
Def Find_pair (A, target): a.sort () i, j = 0, Len (a)-1 while i < j: s = a[i] + a[j] if s = = t Arget: print (i, A[i], J, A[j]) i + = 1 J-= 1 elif s < target: i + = 1 Else: J-= 1
if __name__ = = "__main__": A = [0, 1, 1, 2, one, 8, 3, 4, 5, 6, 7, 8, 9, ten] Find_pair (A, 9)