-
Notifications
You must be signed in to change notification settings - Fork 0
/
4Sum
34 lines (34 loc) Β· 1.16 KB
/
4Sum
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
//Optimized Approach using two pointer - O(n^3) time and O(n) space
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
set<vector<int>> s;
vector<vector<int>> output;
for (int i = 0; i < nums.size(); i++){
for(int j = i+1; j < nums.size(); j++){
int k = j + 1;
int l = nums.size() - 1;
while (k < l) {
//by writing below 4 statement this way it will not give runtime error
long long int sum = nums[i];
sum += nums[j];
sum += nums[k];
sum += nums[l];
if (sum == target) {
s.insert({nums[i], nums[j], nums[k], nums[l]});
k++;
l--;
} else if (sum < target) {
k++;
} else {
l--;
}
}
}
}
for(auto quadruplets : s)
output.push_back(quadruplets);
return output;
}
};