Skip to content

Commit 41dbaab

Browse files
authored
Create two-sum-ii-input-array-is-sorted.cpp
1 parent 825d863 commit 41dbaab

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
vector<int> twoSum(vector<int>& numbers, int target) {
7+
int left = 0, right = numbers.size() - 1;
8+
9+
while (left != right) {
10+
const auto sum = numbers[left] + numbers[right];
11+
if (sum > target) {
12+
--right;
13+
} else if (sum < target) {
14+
++left;
15+
} else {
16+
return {left + 1, right + 1};
17+
}
18+
}
19+
20+
return {0, 0};
21+
}
22+
};

0 commit comments

Comments
 (0)