Title Description
Given a n integer array nums
and a target value target
, it is determined nums
whether there are four elements a, b, c and d, such that A + B + C + d value and target
equal to? Identify all satisfy the conditions of the quad and do not repeat.
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
满足要求的四元组集合为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
Problem-solving ideas
Go CSDN search for "sum" , you can see a similar problem.
This question in 15, and triple the number of basis plus a layer of for
circulation, the idea is the same .
- Sorting + double pointer :
- Use four pointer
(a<b<c<d)
. Fixed minimuma
andb
on thec=b+1
left,d=_size-1
, . Solving two pointers move sandwich. Save makes thenums[a]+nums[b]+nums[c]+nums[d]==target
solution. When too large andd
left, when the smallc
right.c
Andd
when met, expressed in currenta
andb
a minimum value of all the solution has been obtained,b++
into the nextb
cycle, whenb
the end of the loopa++
, the next onea
cycle. I.e., (a
the outermost loop, which is nestedb
loop, again nested double pointerc,d
sandwiched Solution). - To use the double pointer method, the sort must be done der ~. time complexity .
- Solutions reason duplicate because the above solution is a repetitive number may occur when moving the pointer. After so we have to make sure to move the pointer,
the corresponding number to change the job oh.
- Use four pointer
Reference Code
class Solution{
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int> > res;
if(nums.size()<4)
return res;
sort(nums.begin(),nums.end());
int a, b, c, d, _size = nums.size();
for(a = 0; a <= _size-4; a++){
if(a > 0 && nums[a] == nums[a-1])
continue; //确保nums[a] 改变了
for(b = a+1; b <= _size-3; b++){
if(b > a+1 && nums[b] == nums[b-1])
continue; //确保nums[b] 改变了
c = b + 1, d = _size - 1;
while(c < d){
if(nums[a]+nums[b]+nums[c]+nums[d] < target)
c++;
else if(nums[a]+nums[b]+nums[c]+nums[d] > target)
d--;
else{
res.push_back({nums[a], nums[b], nums[c], nums[d]});
while(c < d && nums[c+1]==nums[c]) //确保nums[c] 改变了
c++;
while(c < d&&nums[d-1]==nums[d]) //确保nums[d] 改变了
d--;
c++;
d--;
}
}
}
}
return res;
}
};