Skip to content

Commit aea7707

Browse files
Two Sum II - Input array is sorted
1 parent adf8bff commit aea7707

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Link - https://leetcode.com/problems/two-sum-ii-input-array-is-sorted
2+
3+
/*
4+
167. Two Sum II - Input array is sorted
5+
6+
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
7+
8+
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
9+
10+
Note:
11+
12+
Your returned answers (both index1 and index2) are not zero-based.
13+
You may assume that each input would have exactly one solution and you may not use the same element twice.
14+
15+
16+
Example 1:
17+
18+
Input: numbers = [2,7,11,15], target = 9
19+
Output: [1,2]
20+
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
21+
Example 2:
22+
23+
Input: numbers = [2,3,4], target = 6
24+
Output: [1,3]
25+
Example 3:
26+
27+
Input: numbers = [-1,0], target = -1
28+
Output: [1,2]
29+
30+
31+
Constraints:
32+
33+
2 <= nums.length <= 3 * 104
34+
-1000 <= nums[i] <= 1000
35+
nums is sorted in increasing order.
36+
-1000 <= target <= 1000
37+
*/
38+
39+
class Solution {
40+
public:
41+
vector<int> twoSum(vector<int>& numbers, int target) {
42+
43+
int i = 0, j = numbers.size() - 1;
44+
while(numbers[i] + numbers[j] != target) {
45+
while(numbers[i] + numbers[j] > target) j--;
46+
while(numbers[i] + numbers[j] < target) i++;
47+
}
48+
return {i+1, j+1};
49+
}
50+
};

0 commit comments

Comments
 (0)