问题
Given an array
nums
of n integers and an integertarget
, are there elements a, b, c, and d innums
such that a + b + c + d =target
? Find all unique quadruplets in the array which gives the sum oftarget
.Note:
The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. A solution set is: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ]
分析
像3Sum一样,对nums作升序排序,然后固定a和b,问题就变成了找出c,d 使得c + d = target - a - b 的 2Sum问题. 时间复杂度为
伪代码
4Sum(nums, target)
sort nums by ascending order
initialize set s
n = nums.length
for i = 1 to n - 3
a = nums[i]
for j = i + 1 to n - 2
b = nums[j]
left = j + 1
right = n
expected = target - a - b
while left < right
c = nums[left]
d = nums[right]
if c + d == expected
add a,b,c,d to s
left = left + 1
right -= right + 1
elseif c + d < expected
left = left + 1
else
right = right - 1
initialize array result and fill result with elements of s
return result
优化
上面的算法虽然正确,但在leetcode上运行时有可能会超时,因此需要做一些优化:
- 相同的a,只需要处理一次,同理,相同的b,相同的c,相同的d,都只需要处理一次
- 对于固定的a,a和在紧随a的三个元素的和如果大于target,那么a和任意三个大于a的元素的和肯定也大于target;a和数组最后的三个元素的和如果小于target,那么a和任意三个大于a的元素的和肯定也小于target
- 同理,对于固定的a,b,a,b和在紧随b的两个元素的和如果大于target,那么a,b和任意两个大于b的元素的和肯定也大于target;a,b和数组最后的两个元素的和如果小于target,那么a,b和任意两个大于b的元素的和一定小于target
采用了上述策略后,虽然整体时间复杂度没有优化,但是对于某几类特定的数组,有很好的优化作用,比如所有元素相等的数组,其时间复杂度从减小为
, 即排序的时间复杂度。实际上,对于有许多相等元素的数组,我们的策略都有较好的优化作用
4Sum(nums, target)
sort nums by ascending order
initialize list result
n = nums.length
if n < 4
return empty list
if nums[1] + nums[2] + nums[3] + nums[4] > target
return empty list
if nums[n - 3] + nums[n - 2] + nums[n - 1] + nums[n] < target
return empty list
i = 1
while i <= n - 3
a = nums[i]
if a + nums[i + 1] + nums[i + 2] + nums[i + 3] > target
i = i + 1
continue
if a + nums[n - 2] + nums[n - 1] + nums[n] < target
i = i + 1
continue
j = i + 1
while j <= n - 2
b = nums[j]
if a + b + nums[j + 1] + nums[j + 2] > target
j = j + 1
continue
if a + b + nums[n - 1] + nums[n] < target
j = j + 1
continue
left = j + 1
right = n
expected = target - a - b
while left < right
c = nums[left]
d = nums[right]
if c + d == expected
append a,b,c,d to result
repeat
left = left + 1
until left > n or nums[left] != nums[left - 1]
repeat
right = right - 1
until right < 1 or nums[right] != nums[right + 1]
elseif c + d < expected
left = left + 1
else
right = right - 1
repeat
j = j + 1
until j > n - 2 or nums[j] != nums[j - 1]
repeat
i = i + 1
until i > n - 3 or nums[i] != nums[i - 1]
return result