1. Both Sum (https://oj.leetcode.com/problems/two-sum/)
Problem Solving Ideas:
Solution One: Violence, O (N2) time complexity, TLE
Solution two: Using hash, record the subscript of each value in the array, and then iterate through the array again, by looking at whether the value of target-num[i] is in the map to determine another value. Time complexity O (n)
Solution Three: Sort the num array, O (Nlog (n)), then pinch O (n) left and right. But this problem requires record subscript, so this method is not feasible.
The Python code is as follows:
1 deftwosum (self, num, target):2D = {}3Lennum =len (num)4Ans = []5 forIinchxrange (lennum):6D[num[i]] = [I+1]ifNum[i] not inchDElseD[num[i]] + [i+1]7 forIinchNum:8res = target-I9 ifResinchD:Ten ifres = =I: One ifLen (d[i]) = = 2:return(D[i][0], d[i][1]) A Else: - return(D[i][0], d[res][0])ifD[i][0] < d[res][0]Else(D[res][0], d[i][0])
Leetcode Sum correlation algorithm problem