In this Leetcode Two Sum II - Input array is sorted problem solution we have Given an array of integers numbers that are 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.

Leetcode Two Sum II - Input array is sorted problem solution


Problem solution in Python.

class Solution(object):
    def twoSum(self, numbers, target):
        head = 0
        tail = len(numbers) - 1
        while numbers[head] + numbers[tail] != target:
            if numbers[head] + numbers[tail] > target:
                tail -= 1
            else:
                head += 1
        return [head + 1, tail + 1]



Problem solution in Java.

class Solution {
public int[] twoSum(int[] numbers, int target) {
int[]a=new int[2];
int start=0,end=numbers.length-1;
while(start<end)
{
if(numbers[start]+numbers[end]==target)
{
return new int[]{start+1,end+1};

        }
        else  if(numbers[start]+numbers[end]>target)
        {
            end--;
        }
        else
            
        {
            start++;
        }
        
    }
    return new int[2];
    
}
}


Problem solution in C++.

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


Problem solution in C.

int* twoSum(int* numbers, int numbersSize, int target, int* returnSize){
    int i=0,j=numbersSize-1, sum;
	
    while(i<j){
        sum = numbers[i]+numbers[j];
        if(sum<target) i++;
        else if(sum>target) j--;
        else break;
    }
	
    int *dst = (int*)malloc(2*sizeof(int));
    dst[0]=i+1;
    dst[1]=j+1;
    *returnSize=2;
    return dst;
}