Leetcode-18. 四数之和

18. 四数之和

思路:与三数之和相同,采用双指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> res;
int i,j;
int k;
int k1;
int s;
if(nums.size()<=3)
return res;
sort(nums.begin(),nums.end());

for(k=0;k<nums.size()-3;k++)
{
if(nums[k]>target&&target>=0)
break;
if(k>0&&nums[k]==nums[k-1])
continue;
for(k1=k+1;k1<nums.size()-2;k1++)
{
if(k1>k+1&&nums[k1]==nums[k1-1])
continue;
i=k1+1;
j=nums.size()-1;
while(i<j)
{
s=nums[k]+nums[k1]+nums[i]+nums[j]-target;
if(s==0)
{
res.push_back(vector<int>{nums[k],nums[k1],nums[i],nums[j]});
i++;
while(nums[i]==nums[i-1]&&i<j)
i++;
j--;
while(nums[j]==nums[j+1]&&i<j)
j--;
}
else if(s<0)
{
i++;
while(nums[i]==nums[i-1]&&i<j)
i++;
}
else
{
j--;
while(nums[j]==nums[j+1]&&i<j)
j--;
}
}
}
}
return res;
}
};