15. 3Sum(字典)

 

Given an array  nums of  n integers, are there elements  abc in  nums such that  a +  b +  c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

借助 2sum中字典的应用。 时间复杂度 o(n**2)
 1 class Solution(object):
 2     def threeSum(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: List[List[int]]
 6         """
 7         if len(nums) < 3:
 8             return []
 9         nums.sort()
10         res = set()
11         for i, v in enumerate(nums[:-2]):
12             d = {}
13             for x in nums[i+1:]:
14                 if x not in d:
15                     d[-v-x] = 1
16                 else:
17                     res.add((v, -v-x, x))
18         return map(list, res)

猜你喜欢

转载自www.cnblogs.com/zle1992/p/9297010.html