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)
Show Similar Problems
Have you met this question in a real interview?
Yes
No
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
result = []
nums_length = len(nums)
for index in range(nums_length - 1):
if index > 0 and nums[index] == nums[index - 1]:
continue
left = index + 1
right = nums_length - 1
while left < right:
num_sum = nums[left] + nums[right] + nums[index]
if num_sum == 0 and [nums[index], nums[left], nums[right]] not in result:
result.append([nums[index], nums[left], nums[right]])
if num_sum < 0:
left += 1
else:
right -= 1
return result