Problem
Given an array nums
of $n$ integers and an integer target
, are there elements $a$, $b$, $c$, and $d$ in nums
such that $a + b + c + d =$ target
? Find all unique quadruplets in the array which gives the sum of target
.
Note:
The solution set must not contain duplicate quadruplets.
Example:
1 |
|
Explanation
-
Similar to 15. 3Sum. First, we need to sort the input array. Then in the first for loop, we fix the first number. In the second for loop, we fix the second number. We also add the condition that if either these two fix numbers is the same as its previous fix numbers, we
continue
the for loop, so that we don’t have duplicated. -
After we fix the first and second number, we can use two pointers technique. We have
left
andright
that point to the beginning and end side. We sum these four numbers and compare it with the target.-
If they are equal, we will add these four numbers to the result list, and check if
nums[left] == nums[left+1]
, we thenleft +=1
; ifnums[right] == nums[right-1]
, we thenright -= 1
; so that we avoid duplicated; then weleft += 1; right -= 1
to check othernums[left]
andnums[right]
that plus the two fix numbers if they are equal totarget
. -
If the sum is less than target, we will increase
left
. -
If the sum is greater than target, we will decrease
right
.
-
Solution
1 |
|