Skip to content

Commit

Permalink
Create 3Sum.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kshitiz11101 authored Jul 16, 2024
1 parent 302ce4e commit 3ed783c
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions Graphs/3Sum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& arr) {
/*
for (int i = 0; i < n; i++) {
set<int> hashset;
for (int j = i + 1; j < n; j++) {
int third = -(arr[i] + arr[j]);
if (hashset.find(third) != hashset.end()) {
vector<int> temp = {arr[i], arr[j], third};
sort(temp.begin(), temp.end());
st.insert(temp);
}
hashset.insert(arr[j]);
}
}
vector<vector<int>> ans(st.begin(), st.end());
return ans;
*/
int n=arr.size();
sort(arr.begin(), arr.end());
set<vector<int>> st;
vector<int>temp;
int sum=0;
for(int i=0;i<n-2;i++){
int j=i+1,k=n-1;
while(j<k){
sum=arr[i]+arr[j]+arr[k];
if(sum==0){
temp={arr[i],arr[j],arr[k]};
sort(temp.begin(),temp.end());
st.insert(temp);
}
if(sum>0){
k--;
}
else{
j++;
}
}
}
vector<vector<int>> ans(st.begin(), st.end());
return ans;
}
};

0 comments on commit 3ed783c

Please sign in to comment.