15. 3Sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]]
such that i != j
, i != k
, and j != k
, and nums[i] + nums[j] + nums[k] == 0
.
Notice that the solution set must not contain duplicate triplets.
def threeSum(nums):
def twoSum(start, target):
lo, hi = start, L - 1
while (lo < hi):
s = nums[lo] + nums[hi]
if s < target:
lo += 1
elif s > target:
hi -= 1
else:
yield [nums[lo], nums[hi]]
lo += 1
hi -= 1
while lo < hi and nums[lo] == nums[lo - 1]:
lo += 1
res = []
nums.sort()
L = len(nums)
for i in range(L):
if nums[i] > 0:
break
if i == 0 or nums[i - 1] != nums[i]:
for pair in twoSum(i+1, -nums[i]):
res.append([nums[i]] + pair)
return res
Comments
Post a Comment