Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)求3个数的和为0的所有集合解~先对num排序,然后枚举第一个数, 之后设两个指针,l 指向第一个数的后一个,r 指向最后一个数,如果三个数的和小于0,l 后移,如果大于0的话 r 往前移,等于0的话记录结果并且都向中间移~ 注意处理重复解 时间复杂度为O(n^2)
class Solution:
# @return a list of lists of length 3, [[val1,val2,val3]]
def threeSum(self, num):
if num is None or len(num) < 3: return []
num.sort()
res = []
for i in xrange(len(num)):
if i > 0 and num[i] == num[i - 1]:
continue
l, r = i + 1, len(num) - 1
while l < r:
curSum = num[i] + num[l] + num[r]
if curSum == 0:
res.append([num[i], num[l], num[r]])
while l < r and num[l] == num[l + 1]: l += 1
while l < r and num[r] == num[r - 1]: r -= 1
l, r = l + 1, r - 1
elif curSum > 0:
r -= 1
else:
l += 1
return res