Created
August 12, 2021 18:10
-
-
Save gauravkr0071/4e451275c7a99003404e8b631a9ab8d2 to your computer and use it in GitHub Desktop.
Two Sum II - Input array is sorted
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
167. Two Sum II - Input array is sorted | |
Easy | |
Given an array of integers numbers that is already sorted in non-decreasing order, | |
find two numbers such that they add up to a specific target number. | |
Return the indices of the two numbers (1-indexed) as an integer array | |
answer of size 2, where 1 <= answer[0] < answer[1] <= numbers.length. | |
The tests are generated such that there is exactly one solution. | |
You may not use the same element twice. | |
Example 1: | |
Input: numbers = [2,7,11,15], target = 9 | |
Output: [1,2] | |
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. | |
Example 2: | |
Input: numbers = [2,3,4], target = 6 | |
Output: [1,3] | |
Example 3: | |
Input: numbers = [-1,0], target = -1 | |
Output: [1,2] | |
*/ | |
class Solution { | |
public: | |
vector<int> twoSum(vector<int>& numbers, int target) { | |
int end=numbers.size()-1, start=0; | |
vector<int> ans; | |
while(end>start) | |
{ | |
if(numbers[end]+numbers[start]==target) | |
{ans.push_back(start+1);ans.push_back(end+1);return ans;} | |
else if(numbers[end]+numbers[start]<target) | |
start++; | |
else | |
end--; | |
} | |
return ans; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment