-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo_sum2.cpp
More file actions
65 lines (61 loc) · 1.48 KB
/
two_sum2.cpp
File metadata and controls
65 lines (61 loc) · 1.48 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
56
57
58
59
60
61
62
63
64
65
/*
* =====================================================================================
*
* Filename: two_sum2.cpp
*
* Description: Two Sum II - Input array is sorted.
*
* Version: 1.0
* Created: 03/04/19 06:58:15
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <vector>
class Solution
{
public:
std::vector<int> twoSum(const std::vector<int>& numbers, int target)
{
int low;
int high;
for (low = 0, high = numbers.size() - 1; (low < numbers.size() - 1) && (low < high); )
{
int left = target - numbers[high];
if (left < numbers[low])
{
high--;
}
else if (left > numbers[low])
{
low++;
}
else
{
// left == numbers[low]
return std::vector<int>({low + 1, high + 1});
}
}
return std::vector<int>();
}
};
int main(int argc, char* argv[])
{
std::vector<int> numbers = {2, 7, 11, 15};
auto indices = Solution().twoSum(numbers, 9);
if (!indices.empty())
{
printf("Found!");
for (auto idx: indices)
{
printf(" %d", idx);
}
printf("\n");
}
return 0;
}