-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
114 lines (82 loc) · 2.23 KB
/
main.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
98
99
100
101
102
103
104
105
106
107
108
109
110
//
// main.cpp
// 1. Two Sum
//
// Created by 刘畅 on 2017/6/12.
// Copyright © 2017年 刘畅. All rights reserved.
//
#include <iostream>
#include <vector>
#include <map>
using namespace std;
class Solution{
public:
struct cmp{
bool operator()(const pair<int, int> &a, const pair<int, int> &b) const{
return a.first < b.first;
}
};
vector<int> twoSum(vector<int> &nums, int target){
vector<pair<int, int>> newNums;
for(int i = 0; i < nums.size(); i++){
newNums.push_back(make_pair(nums[i],i));
}
sort(newNums.begin(), newNums.end());
vector<int> res;
int pa = 0; int pb = newNums.size() - 1;
while(pa < pb){
if(newNums[pa].first + newNums[pb].first == target){
res.push_back(pa);
res.push_back(pb);
return res;
}
else if (newNums[pa].first + newNums[pb].first < target){
pa++;
}
else
pb--;
}
return res;
}
};
class Solution2{
public:
vector<int> twoSum2(vector<int> &nums, int target){
map<int,int> map;
vector<int> res;
int len = nums.size();
for(int i = 0; i < len; i++){
if(map.count(target-nums[i])){
res.push_back(i);
res.push_back(map[target-nums[i]]);
return res;
}
map[nums[i]] = i;
}
return res;
}
};
int main(int argc, const char * argv[]) {
vector<int> vec;
vector<int> res;
vector<int> res2;
vec.push_back(2);
vec.push_back(7);
vec.push_back(11);
vec.push_back(15);
Solution s = *new Solution();
res = s.twoSum(vec, 9);
cout<<"The first method is ";
for(int i = 0; i < res.size(); i++){
cout<<res[i]<<" ";
}
cout<<endl;
Solution2 s2 = *new Solution2();
res2 = s2.twoSum2(vec, 9);
cout<<"The second method is ";
for(int i = 0; i < res2.size(); i++){
cout<<res2[i]<<" ";
}
cout<<endl;
return 0;
}