Problem Statement
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.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Input and Output
Input and Output
Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2
Link to GitHub :Code
- We need array to store the indices
- Check if the array is empty or contains less than 2 elements
- Define the start and the end point of the array
- Iterate till condition is met
- Check if the sum is equal to the target. If yes get the indices.
- If condition is not met then traverse left or right based on the sum value
- Traverse to the right
- Traverse to the left
package Algorithms.Arrays; public class TwoSumIIInputSorted { public static int [] get(int [] arr, int target) { //array to store the indices int [] indices = new int[2]; //Check if the array is empty or contains less than 2 elements if (arr ==null || arr.length <2 ) return indices; //define the start and the end point of the array int start=0;int end=arr.length-1; //iterate till condition is met while(start <end) { //Sum the first and last element in the array int sum=arr[start]+arr[end]; //check if the sum is equal to the target. If yes get the indice if(sum==target) { //Note we need indice, so we need to increement indices[0]=start+1; indices[1]=end+1; } //move to the right else if(sum > target) { end--; } //traverse to the left else { start++; } } return indices; } }
No comments:
Post a Comment