-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15.3-sum.cpp
More file actions
48 lines (46 loc) · 1.4 KB
/
Copy path15.3-sum.cpp
File metadata and controls
48 lines (46 loc) · 1.4 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
/*
* @lc app=leetcode id=15 lang=cpp
*
* [15] 3Sum
*/
// @lc code=start
#include "bits/stdc++.h"
using namespace std;
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
// two pointers
// sort first
sort(nums.begin(), nums.end());
// 1. fix the first number
for (int i = 0; i < nums.size() - 2; ++i) {
// 2. skip the duplicate triplet
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int r = nums.size() - 1;
int target = -nums[i];
for (int l = i + 1; l < nums.size() - 1; ++l) {
// 3. skip the duplicate pair
if (l > i + 1 && nums[l] == nums[l - 1]) {
continue;
}
// 4. move the right pointer to find the targetable number
while (l < r && nums[l] + nums[r] > target) {
--r;
}
// 5. if the left pointer meets the right pointer, break
if (l == r) {
break;
}
// 6. if the sum is 0, add the triplet to the result
if (nums[l] + nums[r] == target) {
res.push_back({nums[i], nums[l], nums[r]});
}
}
}
return res;
}
};
// @lc code=end