-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlc-3Sum.cpp
More file actions
31 lines (27 loc) · 755 Bytes
/
lc-3Sum.cpp
File metadata and controls
31 lines (27 loc) · 755 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
// Contains the solution function to 3sum problem from leetcode
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> a;
sort(nums.begin(), nums.end());
int n=nums.size();
for(int i=0;i<nums.size();++i){
int j=i+1;
int k=n-1;
if(i>0 && nums[i]==nums[i-1])
continue;
while(j<k){
if(k<n-1 && nums[k]==nums[k+1]){
k--;
continue;
}
if(nums[i] + nums[j] + nums[k] > 0)
k--;
else if(nums[i] + nums[j] + nums[k] < 0)
j++;
else{
a.push_back({nums[i], nums[j], nums[k]});
++j, --k;
}
}
}
return a;
}