-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4-sum.cpp
More file actions
51 lines (39 loc) · 1.29 KB
/
Copy path4-sum.cpp
File metadata and controls
51 lines (39 loc) · 1.29 KB
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
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
int n = nums.size();
for (int i=0; i < n-3; i++){
if(i > 0 && nums[i] == nums[i-1]){
continue;
}
for(int l=i+1; l < n-2; l++){
if(l > i+1 && nums[l] == nums[l-1]){
continue;
}
int j = l+1;
int k = nums.size()-1;
while(j < k){
long long sum = (long long)nums[i] + nums[l] + nums[j] + nums[k];
if(sum == target){
result.push_back({nums[i], nums[l], nums[j], nums[k]});
while(j<k && nums[j] == nums[j+1]){
j++;
}
while(j<k && nums[k] == nums[k-1]){
k--;
}
j++;
k--;
} else if (sum > target){
k--;
} else {
j++;
}
}
}
}
return result;
}
};