问题
Given an array
nums
of n integers, are there elements a, b, c innums
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] ]
分析
先对数组nums排序,然后固定第一个数a,则问题可以转化为在比a大的元素中,找到b, c,使得b + c = -a, 所以我们可以使用2sum的解法遭到b, c。
a有n个取值,2sum的时间复杂度为O(n), 所以3sum的时间复杂度为
如果需要去重,可以使用集合去除重复的a,b,c
伪代码
3Sum(nums)
sort nums by ascending order
initialize set s
n = nums.length
for i = 1 to n - 2
a = nums[i]
left = i + 1
right = n
while left < right
if nums[left] + nums[right] < -a
left = left + 1
elseif nums[left] + nums[right] > -a
right = right - 1
else
add a,b,c to s
left = left + 1
right = right - 1
initialize array result and fill result with elements of s
return result