classSolution: deftwoSum(self, nums: List[int], target: int) -> List[int]: dic = {} for i in range(len(nums)): if nums[i] in dic: return [dic[nums[i]], i] else: dic[target - nums[i]] = i
第二种方法:暴力两重遍历,这样时间复杂度是O(n^2),在LeetCode里提交会超时
1 2 3 4 5 6
classSolution: deftwoSum(self, nums: List[int], target: int) -> List[int]: for i in range(len(nums)): for j in range(i+1, len(nums)): if nums[i] + nums[j] == target: return [i, j]
classSolution(object): defthreeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ if len(nums) < 3: return [] nums.sort() res = set() for i, v in enumerate(nums[:-2]) : if i >= 1and v == nums[i-1]: continue d = {} for x in nums[i+1:]: if x notin d: d[-(v+x)] = 1 else: res.add((v, -(v+x), x)) return map(list, res)
classSolution(object): defthreeSum(self, nums): if len(nums) < 3: return [] nums.sort() res = [] for i, x in enumerate(nums[:-2]): if i >= 1and x == nums[i-1]: continue l, r = i+1, len(nums)-1 while l < r: s = nums[i] + nums[l] + nums[r] if s < 0: l += 1 elif s > 0: r -= 1 else: res.append((nums[i], nums[l], nums[r])) while l < r and nums[l] == nums[l+1]: l += 1 while l < r and nums[r] == nums[r-1]: r -= 1 l += 1 r -= 1 return res