第一次提交
1 class Solution(object): 2 def twoSum(self, nums, target): 3 """ 4 :type nums: List[int] 5 :type target: int 6 :rtype: List[int] 7 """ 8 length = len(nums) 9 for i in range(length-1): 10 for j in range(i+1, length): 11 if nums[i] + nums[j] == target: 12 self = [i,j] 13 return self
执行用时1990ms 时间复杂度还是O(n2)
因为这是用的数组的方式求解,后面用哈希求解时时间复杂度会降到O(1)
方法二:哈希
Python中用dict来实现哈希
用下标i遍历数组,每个都看看哈希表里有没有满足target - nums[i]的key,有的话return答案,没有的话就存入i及对应值
1 class Solution(object): 2 def twoSum(self, nums, target): 3 """ 4 :type nums: List[int] 5 :type target: int 6 :rtype: List[int] 7 """ 8 length = len(nums) 9 help_dict = {} 10 i = 0 11 while i < length: 12 if target - nums[i] in help_dict: 13 return [i, help_dict[target - nums[i]]] 14 else: 15 help_dict[nums[i]] = i 16 i += 1 17 return [] 18 19