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:
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
class Solution: # @return a list of lists of length 3, [[val1,val2,val3]] def threeSum(self, num): if not num or len(num)<3: return [] num = sorted(num) res = set() for i in range(len(num)): l = i+1 h = len(num)-1 while l < h: if num[l] + num[h] > - num[i]: h -= 1 elif num[l] + num[h] < - num[i]: l += 1 else: res.add((num[i],num[l],num[h])) l += 1 return [list(t) for t in res]