Python algorithm-to quickly find the two numbers that meet the condition, the premise is that such two numbers must exist.
I don't want to write about the solution.
At first, I thought of solution 2. the last hash table.
(Actually, I want to create an array as big as target .. if the index exists, it is written to the index, but to find all the data, the two-dimensional array is required. However, if the target is large, is it a waste of space... so change to Dict)
Only two numbers are required for the question --
More interesting expansion problems
It should not be difficult to find three, but it is unclear about others. I would like to add more...
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, 11, 8, 3, 4, 5, 6, 7, 8, 9, 10] find_pair(A, 9)
2. dictionary
def find_pair(A, target): B = {} for i in range(0, len(A)): if A[i] <= target: if not B.has_key(A[i]): 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, 10] find_pair(A, 9)
3. this method has been re-sorted, and I don't know what the meaning of the index returned in the book is... the sorting is lazy and 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 == target: 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, 11, 8, 3, 4, 5, 6, 7, 8, 9, 10] find_pair(A, 9)