-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTwoSum.cpp
97 lines (82 loc) · 2.48 KB
/
TwoSum.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<int> twoSum(vector<int>& nums, int target) {
auto length = nums.size();
int temp=0;
unordered_multimap<int,int> m;
for(auto i=0;i<length;i++) {
m.insert({nums[i],i});
}
vector<int> result;
result.clear();
for(auto itr=m.begin(); itr != m.end(); itr++) {
temp = target - itr->first;
if(m.find(temp) != m.end()) {
if(m.find(temp)->first != itr->first) {
result.push_back(itr->second);
result.push_back(m.find(temp)->second);
break;
} else if (m.count(temp) > 1) {
result.push_back(itr->second);
result.push_back((++itr)->second);
break;
}
}
}
sort(result.begin(),result.end());
return result;
}
};
void trimLeftTrailingSpaces(string &input) {
input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) {
return !isspace(ch);
}));
}
void trimRightTrailingSpaces(string &input) {
input.erase(find_if(input.rbegin(), input.rend(), [](int ch) {
return !isspace(ch);
}).base(), input.end());
}
vector<int> stringToIntegerVector(string input) {
vector<int> output;
trimLeftTrailingSpaces(input);
trimRightTrailingSpaces(input);
input = input.substr(1, input.length() - 2);
stringstream ss;
ss.str(input);
string item;
char delim = ',';
while (getline(ss, item, delim)) {
output.push_back(stoi(item));
}
return output;
}
int stringToInteger(string input) {
return stoi(input);
}
string integerVectorToString(vector<int> list, int length = -1) {
if (length == -1) {
length = list.size();
}
if (length == 0) {
return "[]";
}
string result;
for(int index = 0; index < length; index++) {
int number = list[index];
result += to_string(number) + ", ";
}
return "[" + result.substr(0, result.length() - 2) + "]";
}
int main() {
string line;
while (getline(cin, line)) {
vector<int> nums = stringToIntegerVector(line);
getline(cin, line);
int target = stringToInteger(line);
vector<int> ret = Solution().twoSum(nums, target);
string out = integerVectorToString(ret);
cout << out << endl;
}
return 0;
}