|
1 | 1 | class Solution {
|
2 | 2 | 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--; |
12 | 15 | }
|
13 |
| - else if(nums[l] + nums[r] < sum) |
| 16 | + else if (nums[l] + nums[r] < sum) |
14 | 17 | l++;
|
15 | 18 | else
|
16 | 19 | r--;
|
17 | 20 | }
|
18 | 21 |
|
19 | 22 | return vec;
|
20 | 23 | }
|
21 |
| - |
| 24 | + |
22 | 25 | vector<vector<int>> threeSum(vector<int>& nums) {
|
23 | 26 | int n = nums.size();
|
24 | 27 | // [- - - - - - - -]
|
25 | 28 | // a + b + c = 0
|
26 |
| - sort(nums.begin(), nums.end()); |
27 |
| - vector<vector<int>> triplets; |
| 29 | + |
| 30 | + sort(nums.begin(), nums.end());// sorted array |
28 | 31 |
|
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++) { |
32 | 38 |
|
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; |
34 | 42 |
|
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 | + } |
38 | 55 | }
|
39 | 56 | }
|
40 |
| - |
41 |
| - while(a == nums[i] and i < n - 2) i++; |
| 57 | + |
| 58 | + // while(a == nums[i] and i < n - 2) i++; |
42 | 59 | }
|
43 | 60 |
|
44 | 61 | return triplets;
|
45 | 62 | }
|
46 | 63 | };
|
47 | 64 |
|
| 65 | +// NOT while(l <= r) bcoz l != r |
| 66 | +// NOT p2(i+1,n) bcoz right limit should be n-1 |
| 67 | + |
| 68 | + |
| 69 | + |
48 | 70 |
|
49 | 71 |
|
50 | 72 |
|
|
0 commit comments