. 1 Import Time 2 . 3 # Method a: . 4 class Solution: . 5 DEF twoSum (Self, the nums, target): . 6 for I in Range (len (the nums)): # listing first cycle . 7 for J in Range (len ( the nums) -1 ): # listing should be the second cycle of the first cycle of the digital excluded . 8 IF the nums [I] == the nums [J]: # result is not the same number . 9 Pass 10 elif the nums [I ] + the nums [J] == target: . 11 return J, I 12 is the else : 13 is Continue 14 15 # Method two: 16 class Solution: . 17 DEF twoSum (Self, the nums, target): 18 is for I in Range (len (the nums)): . 19 IF target -nums [I] in the nums and I = nums.index (target! - the nums [I]): # the same element if the difference, the index returns two elements and not in the list 20 is return [I, nums.index (target - the nums [I])] 21 is the else : 22 is Continue 23 is 24 # method three 25 class Solution: 26 DEF twoSum (Self, nums, target): 27 = DIC {} 28 for I, NUM in the enumerate (the nums): # a list of all the elements according to the first index value, the number is placed in the dictionary mode key. 29 DIC [NUM] = I 30 for I, NUM in the enumerate (the nums): 31 is J = DIC [target- NUM] # key difference is to look in the dictionary there is no corresponding value. 32 IF ! I = J and J IS Not None: 33 is return [I, J] 34 is 35 T1 = time.perf_counter () 36 Solution = Solution () 37 [ A = solution.twoSum ([2,7,11,15, 2,6,98,23], 13) 38 t2 = time.perf_counter() 39 print(a) 40 print(t2-t1)
One of the most conventional method of thinking, that is, nested loops, constantly variable list. The second method used a loop, reducing the value of each target view cycle is in the list. Method three used the dictionary and improve efficiency