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[] = { 2, 7, 11, 15 };int target = 9;int result[] = twoSum(nums, target);System.out.println(Arrays.toString(result));}// two sum index equals target using two pointer approachpublic static int[] twoSum(int[] nums, int target) {int low = 0;int high = nums.length - 1;// iterate till low<=highwhile (low <= high) {// if sum equalsif ((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 approachvector<int> twoSum(int nums[],int n, int target){vector<int > v;int low = 0;int high=n-1;// iterate till low<=highwhile (low <= high){// if sum equalsif ((nums[low] + nums[high]) == target){v.push_back(low+1);v.push_back(high+1);break;}// move pointerelse if ((nums[low] + nums[high]) > target) {high--;} else {low++;}}return v;}int main(){int arr[] = { 2, 7, 11, 15 };int target = 9;int n=sizeof(arr)/sizeof(arr[0]);vector<int> res= twoSum(arr,n, target);for(int i=0;i<res.size();i++)cout<<res[i]<<" ";return 0;}
No comments:
Post a Comment