167. Two Sum II - Input array is sorted (Leetcode)

PHOTO EMBED

Wed Oct 06 2021 07:45:46 GMT+0000 (Coordinated Universal Time)

Saved by @Sakshamkashyap7 #c++

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int i = 0, j = numbers.size() - 1;
        while(i < j) {
            int sum = numbers[i] + numbers[j];
            if(sum == target) return {i + 1, j + 1};
            else if(sum > target)  j--;
            else    i++;
        }
        return {};
    }
};
content_copyCOPY

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.

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/