LeetCode 18. 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.
Example:
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]
]
分析:
首先,判断数组长度,若小于4,直接返回空二维vector;
将数组按从小到大排序,先确定nums[i]为第一个元素,nums[j]为第二个元素,为了避免重复,如果nums[i]和nums[i-1]相等就continue,如果nums[j]和nums[j-1]相等就continue,然后设定两个变量begin和end,begin指向j+1,end指向n-1;
判断此时sum是否等于target,如果等于target就将nums[i],nums[j],nums[begin],nums[end]放入result数组中,且begin++
,end--
,为了避免重复,如果begin++
后的元素依旧和刚才的元素相等,继续begin++
,end同理
如果sum大于target,则end--
;若果sum小于target,就将begin++
;
最后返回result二维数组。
代码如下:
1 |
|