Two Sum II - Input array is sorted

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. 

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.

Approach

Java


import java.util.Arrays;

public class TwoSumII {
    public static void main(String[] args) {
        int nums[] = { 271115 };
        int target = 9;
        int result[] = twoSum(nums, target);
        System.out.println(Arrays.toString(result));
    }

    // two sum index equals target using two pointer approach
    public static int[] twoSum(int[] numsint target) {
        int low = 0;
        int high = nums.length - 1;
        // iterate till low<=high
        while (low <= high) {
            // if sum equals
            if ((nums[low] + nums[high]) == target) {
                return new int[] { low + 1, high + 1 };
                // move pointer
            } else if ((nums[low] + nums[high]) > target) {
                high--;
            } else {
                low++;
            }
        }
        return null;

    }
}

C++

#include <bits/stdc++.h>
using namespace std;
// two sum index equals target using two pointer approach
vector<int>  twoSum(int nums[],int nint target
{

       vector<int > v;
        int low = 0;
        int high=n-1;
        // iterate till low<=high
        while (low <= high
        {
            // if sum equals
            if ((nums[low] + nums[high]) == target)
                {
                    v.push_back(low+1);
                    v.push_back(high+1);
                    break;
                }
                // move pointer
            else if ((nums[low] + nums[high]) > target) {
                high--;
            } else {
                low++;
            }
        }
        return v;

}

int main()
{
    int arr[] = { 271115 };
    int target = 9;
    int n=sizeof(arr)/sizeof(arr[0]);
    vector<intrestwoSum(arr,ntarget);
    for(int i=0;i<res.size();i++)
       cout<<res[i]<<" ";
    return 0;
}


No comments:

Post a Comment