-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path167. Two Sum II - Input array is sorted lnk
75 lines (65 loc) · 1.86 KB
/
167. Two Sum II - Input array is sorted lnk
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
//https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {/
int i=0,j=numbers.size()-1;
while(numbers[i] + numbers[j] != target){
if(numbers[i] + numbers[j] < target)i++;
else j--;
}
return {i+1,j+1};
}
};
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> numbers = stringToIntegerVector(line);
getline(cin, line);
int target = stringToInteger(line);
vector<int> ret = Solution().twoSum(numbers, target);
string out = integerVectorToString(ret);
cout << out << endl;
}
return 0;
}