forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main3.cpp
62 lines (48 loc) · 1.37 KB
/
main3.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
/// Source : https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/
/// Author : liuyubobobo
/// Time : 2017-11-13
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
// Two Pointers
// Time Complexity: O(n)
// Space Complexity: O(1)
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
assert(numbers.size() >= 2);
// assert(isSorted(numbers));
int l = 0, r = numbers.size() - 1;
while(l < r){
if(numbers[l] + numbers[r] == target){
int res[2] = {l+1, r+1};
return vector<int>(res, res+2);
}
else if(numbers[l] + numbers[r] < target)
l ++;
else // numbers[l] + numbers[r] > target
r --;
}
throw invalid_argument("the input has no solution");
}
private:
bool isSorted(const vector<int>& numbers){
for(int i = 1 ; i < numbers.size() ; i ++)
if(numbers[i] < numbers[i-1])
return false;
return true;
}
};
void printVec(const vector<int>& vec){
for(int e: vec)
cout << e << " ";
cout << endl;
}
int main() {
int nums[] = {2, 7, 11, 15};
vector<int> vec(nums, nums + sizeof(nums) / sizeof(int));
int target = 9;
printVec(Solution().twoSum(vec, target));
return 0;
}