4Sum
https://leetcode.com/problems/4sum/description/
Given an array S of n integers, are there elements a, b, c, and d in S 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.
For example, given array S = [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]
]
Thoughts
和3sum同理,只是要多加一层循环。
Code
Analysis
Errors:
while (l < r && nums[r] == nums[r + 1]) 没写在else里
if (j > 0 && nums[j] == nums[j - 1]) 导致[0,0,0,0]没有执行
忘了sort
时间复杂度O(n^3)
做题耗时:20min
Last updated
Was this helpful?