Skip to content

Commit 4352257

Browse files
1 parent 6930ffc commit 4352257

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed

TwoSum.cpp

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
class Solution {
2+
public:
3+
vector<int> twoSum(vector<int>& nums, int target) {
4+
auto length = nums.size();
5+
int temp=0;
6+
unordered_multimap<int,int> m;
7+
8+
for(auto i=0;i<length;i++) {
9+
m.insert({nums[i],i});
10+
11+
}
12+
13+
vector<int> result;
14+
result.clear();
15+
for(auto itr=m.begin(); itr != m.end(); itr++) {
16+
temp = target - itr->first;
17+
18+
if(m.find(temp) != m.end()) {
19+
if(m.find(temp)->first != itr->first) {
20+
result.push_back(itr->second);
21+
result.push_back(m.find(temp)->second);
22+
break;
23+
} else if (m.count(temp) > 1) {
24+
result.push_back(itr->second);
25+
result.push_back((++itr)->second);
26+
break;
27+
}
28+
}
29+
30+
}
31+
sort(result.begin(),result.end());
32+
return result;
33+
}
34+
};
35+
36+
void trimLeftTrailingSpaces(string &input) {
37+
input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) {
38+
return !isspace(ch);
39+
}));
40+
}
41+
42+
void trimRightTrailingSpaces(string &input) {
43+
input.erase(find_if(input.rbegin(), input.rend(), [](int ch) {
44+
return !isspace(ch);
45+
}).base(), input.end());
46+
}
47+
48+
vector<int> stringToIntegerVector(string input) {
49+
vector<int> output;
50+
trimLeftTrailingSpaces(input);
51+
trimRightTrailingSpaces(input);
52+
input = input.substr(1, input.length() - 2);
53+
stringstream ss;
54+
ss.str(input);
55+
string item;
56+
char delim = ',';
57+
while (getline(ss, item, delim)) {
58+
output.push_back(stoi(item));
59+
}
60+
return output;
61+
}
62+
63+
int stringToInteger(string input) {
64+
return stoi(input);
65+
}
66+
67+
string integerVectorToString(vector<int> list, int length = -1) {
68+
if (length == -1) {
69+
length = list.size();
70+
}
71+
72+
if (length == 0) {
73+
return "[]";
74+
}
75+
76+
string result;
77+
for(int index = 0; index < length; index++) {
78+
int number = list[index];
79+
result += to_string(number) + ", ";
80+
}
81+
return "[" + result.substr(0, result.length() - 2) + "]";
82+
}
83+
84+
int main() {
85+
string line;
86+
while (getline(cin, line)) {
87+
vector<int> nums = stringToIntegerVector(line);
88+
getline(cin, line);
89+
int target = stringToInteger(line);
90+
91+
vector<int> ret = Solution().twoSum(nums, target);
92+
93+
string out = integerVectorToString(ret);
94+
cout << out << endl;
95+
}
96+
return 0;
97+
}

0 commit comments

Comments
 (0)