-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlec_15.cpp
97 lines (77 loc) Β· 2.52 KB
/
lec_15.cpp
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& v) {
int n = v.size();
set<vector<int>>st;
for(int i = 0 ;i<n;i++){
for(int j = i+1 ; j<n;j++){
for(int k = j+1 ; k<n;k++){
if(v[i] + v[j] + v[k] == 0){
vector<int> temp = {v[i] ,v[j] ,v[k] };
sort(temp.begin() , temp.end());
st.insert(temp);
}
}
}
}
vector<vector<int>> ans(st.begin() , st.end());
return ans;
}
};
//
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& arr) {
int n = arr.size();
set<vector<int>> st;
for (int i = 0; i < n; i++) {
set<int> hashset;
for (int j = i + 1; j < n; j++) {
//Calculate the 3rd element:
int third = -(arr[i] + arr[j]);
//Find the element in the set:
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]);
}
}
//store the set in the answer:
vector<vector<int>> ans(st.begin(), st.end());
return ans;
}
};
// pointer approach
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& arr) {
int n = arr.size();
vector<vector<int>>ans;
sort(arr.begin() , arr.end());
for(int i = 0 ; i<n;i++){
if( i!= 0 && arr[i] == arr[i-1]) continue;// remove duplicates
int j = i+1;
int k = n-1;
while(j<k){
int sum = arr[i] + arr[j] + arr[k];
if(sum<0){
j++;
}
else if( sum>0){
k--;
}
else{
vector<int>temp = {arr[i] ,arr[j],arr[k]};
ans.push_back(temp);
j++;
k--;
while(j<k && arr[j] == arr[j-1]) j++;
while(j<k && arr[k] == arr[k+1]) k--;
}
}
}
return ans;
}
};