forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path167-Two-Sum-II.cpp
More file actions
34 lines (28 loc) · 773 Bytes
/
167-Two-Sum-II.cpp
File metadata and controls
34 lines (28 loc) · 773 Bytes
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
/*
Given a 1-indexed sorted int array & target:
Return indices (added by 1) of 2 nums that add to target
2 pointers, outside in, iterate i/j if sum is too low/high
Time: O(n)
Space: O(1)
*/
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int i = 0;
int j = numbers.size() - 1;
vector<int> result;
while (i < j) {
int sum = numbers[i] + numbers[j];
if (sum < target) {
i++;
} else if (sum > target) {
j--;
} else {
result.push_back(i + 1);
result.push_back(j + 1);
break;
}
}
return result;
}
};