Skip to content

Commit 29b611d

Browse files
committed
Time: 125 ms (66.18%), Space: 21 MB (48.23%) - LeetHub
1 parent 30dcc9d commit 29b611d

File tree

1 file changed

+44
-22
lines changed

1 file changed

+44
-22
lines changed

15-3sum/15-3sum.cpp

+44-22
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,72 @@
11
class Solution {
22
public:
3-
vector<pair<int,int>> p2(int l, int r, vector<int>& nums, int sum) {
4-
vector<pair<int,int>> vec;
5-
while(l < r) {
6-
if(nums[l] + nums[r] == sum) {
7-
vec.push_back({l, r});
8-
int ll = nums[l];
9-
int rr = nums[r];
10-
while(ll == nums[l] and l < r) l++;
11-
while(rr == nums[r] and l < r) r--;
3+
vector<pair<int, int>> p2(int l, int r, vector<int>& nums, int sum) {
4+
vector<pair<int, int>> vec;
5+
while (l < r) {
6+
if (nums[l] + nums[r] == sum) {
7+
vec.push_back({l, r});
8+
9+
10+
int ll = nums[l];
11+
while (ll == nums[l] and l < r) l++;
12+
13+
int rr = nums[r];
14+
while (rr == nums[r] and l < r) r--;
1215
}
13-
else if(nums[l] + nums[r] < sum)
16+
else if (nums[l] + nums[r] < sum)
1417
l++;
1518
else
1619
r--;
1720
}
1821

1922
return vec;
2023
}
21-
24+
2225
vector<vector<int>> threeSum(vector<int>& nums) {
2326
int n = nums.size();
2427
// [- - - - - - - -]
2528
// a + b + c = 0
26-
sort(nums.begin(), nums.end());
27-
vector<vector<int>> triplets;
29+
30+
sort(nums.begin(), nums.end());// sorted array
2831

29-
for(int i = 0; i < n - 2; ) {
30-
int a = nums[i];
31-
vector<pair<int,int>> p = p2(i+1,n-1,nums,-a);
32+
// misc case
33+
if(nums[n-1] < 0)
34+
return {};
35+
vector<vector<int>> triplets;
36+
37+
for (int i = 0; i < n - 2; i++) {
3238

33-
int sz = p.size();
39+
// misc: 1st element is > 0, then not possible for triplet sum = 0
40+
if(nums[i] > 0)
41+
break;
3442

35-
if(sz) {
36-
for(auto pp: p) {
37-
triplets.push_back({a, nums[pp.first], nums[pp.second]});
43+
if (i == 0 or nums[i - 1] < nums[i]) {
44+
// distinct i
45+
46+
int a = nums[i];
47+
vector<pair<int, int>> p = p2(i + 1, n - 1, nums, -a);
48+
49+
int sz = p.size();
50+
51+
if (sz) {
52+
for (auto pp : p) {
53+
triplets.push_back({a, nums[pp.first], nums[pp.second]});
54+
}
3855
}
3956
}
40-
41-
while(a == nums[i] and i < n - 2) i++;
57+
58+
// while(a == nums[i] and i < n - 2) i++;
4259
}
4360

4461
return triplets;
4562
}
4663
};
4764

65+
// NOT while(l <= r) bcoz l != r
66+
// NOT p2(i+1,n) bcoz right limit should be n-1
67+
68+
69+
4870

4971

5072

0 commit comments

Comments
 (0)