[LC] 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]
]

Time: O(N^2)
 1 class Solution:
 2     def threeSum(self, nums: List[int]) -> List[List[int]]:
 3         res = []
 4         if nums is None:
 5             return res
 6         
 7         nums.sort()
 8         for i in range(len(nums) - 2):
 9             if i > 0 and nums[i] == nums[i - 1]:
10                 continue
11             target = -nums[i]
12             left = i + 1
13             right = len(nums) - 1
14             while left < right:
15                 if nums[left] + nums[right] == target:
16                     lst = [nums[i], nums[left], nums[right]]
17                     res.append(lst)
18                     left += 1
19                     right -= 1
20                     while left < right and nums[left] == nums[left - 1]:
21                         left += 1
22                     while left < right and nums[right] == nums[right + 1]:
23                         right -= 1
24                 elif nums[left] + nums[right] < target:
25                     left += 1
26                 else:
27                     right -= 1
28         return res
29         

猜你喜欢

转载自www.cnblogs.com/xuanlu/p/11652420.html