3Sum
Given an array nums
of n integers, find all unique triplets in the array that add up to a specific target sum.
Here are some key points to understand about the problem:
- The goal is to find all unique triplets in the array
nums
such that a + b + c = 0, where a, b, and c are elements ofnums
. - The solution set must not contain duplicate triplets.
- Sort the given array
nums
in ascending order. - Initialize an empty array
result
to store the triplets. - Iterate through the array using a loop variable
i
from 0 to n-2.- Skip duplicates: If
i > 0
andnums[i] == nums[i-1]
, continue to the next iteration. - Set
target
as the negation ofnums[i]
. - Use two pointers,
left
starting fromi + 1
andright
starting fromn - 1
.
- Skip duplicates: If
- Within the loop, while
left < right
, calculate the sumsum = nums[i] + nums[left] + nums[right]
.- If
sum == 0
, add the triplet[nums[i], nums[left], nums[right]]
to theresult
. - Skip duplicates: Increment
left
whilenums[left] == nums[left + 1]
, and decrementright
whilenums[right] == nums[right - 1]
. - Increment
left
and decrementright
. - If
sum < 0
, incrementleft
; otherwise, decrementright
.
- If
- Return the
result
array containing all unique triplets.