-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo_sum_2.cpp
More file actions
55 lines (51 loc) · 1.31 KB
/
Copy pathtwo_sum_2.cpp
File metadata and controls
55 lines (51 loc) · 1.31 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
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int numbers_size = numbers.size();
auto forward_index = 0;
auto backforward_index = numbers_size - 1;
std::vector<int> result;
for(; (backforward_index > 0) && (forward_index < numbers_size); )
{
if(backforward_index <= forward_index)
{
break;
}
int sum = numbers[forward_index] + numbers[backforward_index];
if(sum > target)
{
backforward_index--;
continue;
}
else if(sum < target)
{
forward_index++;
continue;
}
if(sum == target)
{
result.push_back(forward_index+1);
result.push_back(backforward_index+1);
break;
}
}
return result;
}
};
int main(void)
{
Solution solution;
std::vector<int> numbers = {2,3,4};
int target = 6;
std::vector<int> result;
result = solution.twoSum(numbers,target);
for(auto& itr : result)
{
std::cout << itr << " ";
}
std::cout << std::endl;
return 0;
}