-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3Sum.cpp
More file actions
67 lines (65 loc) · 1.78 KB
/
Copy path3Sum.cpp
File metadata and controls
67 lines (65 loc) · 1.78 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include<iostream>
#include<vector>
#include<map>
using namespace std;
class Solution
{
public:
vector<vector<int> > threeSum(vector<int> &num)
{
vector<vector<int> >ret;
multimap<int,int> sum;
size_t i=0;
for(i=0; i<num.size(); i++)
sum.insert({num[i],i});
auto map_it=sum.begin();
while(map_it!=sum.end())
{
int target=-map_it->first;
//第二个迭代器从第一个迭代器的后面位置开始
auto sec=map_it;
sec++;
map<int,int>::iterator iter;
while(sec!=sum.end())
{
int tmp=target-sec->first;
//第三个迭代器只能在出去第一个和第二个元素之后的剩余内容中查找
auto third=sec;
third++;
multimap<int,int> sum1(third,sum.end());
iter=sum1.find(tmp);
if(iter!=sum1.end())
break;
sec++;
}
if(sec!=sum.end())
{
cout<<map_it->first<<endl;
cout<<sec->first<<" "<<iter->first<<endl;
vector<int> tmp={map_it->first,sec->first,iter->first};
for(i=0;i<(int)ret.size();i++)
{
if(ret[i]==tmp)
break;
}
if(i>=(int)ret.size())
ret.push_back(tmp);
}
map_it++;
}
return ret;
}
};
int main()
{
vector<int> vec={-1,0,1,2,-1,-4};
Solution s;
vector<vector<int> > result=s.threeSum(vec);
for(auto a:result)
{
for(auto v:a)
cout<<v<<" ";
cout<<endl;
}
cout<<endl;
}