forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0015.cpp
More file actions
executable file
·39 lines (36 loc) · 794 Bytes
/
LC0015.cpp
File metadata and controls
executable file
·39 lines (36 loc) · 794 Bytes
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
/*
Problem Statement: https://leetcode.com/problems/3sum/
Time: O(n²)
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
vector<vector<int>> threeSum(vector<int> nums) {
int l, r, sum, n = nums.size();
vector<vector<int>> triplets;
sort(nums.begin(), nums.end());
for (int i = 0; i < n && nums[i] <= 0; i++) {
if (i > 0 && nums[i] == nums[i - 1])
continue;
l = i + 1;
r = n - 1;
while (l < r) {
sum = nums[i] + nums[l] + nums[r];
if (sum == 0) {
triplets.push_back({nums[i], nums[l], nums[r]});
while (l < r && nums[l] == nums[l + 1])
l++;
while (l < r && nums[r] == nums[r - 1])
r--;
l++;
}
else if (sum < 0)
l++;
else
r--;
}
}
return triplets;
}
};