2 solutions; using HashMap and w/o using HashMap
From https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/#/description
public class Solution {
public int[] twoSum(int[] numbers, int target) {
// ****** solution without using HashMap ***** //
int index[] = new int[2];
int i = 0, j = numbers.length -1; // i - left , j - right
while( i <numbers.length ){
int rem = numbers[i] + numbers[j];
if(rem == target){
index[0] = i + 1;
index[1] = j + 1;
break;
}
else if(rem < target){
i++;
}else{
j--;
}
}
return index;
// ******** Solution using HashMap ******* //
// Map<Integer,Integer> map = new HashMap<>();
// int i=1;
// int ans[] = new int[2];
// for(int num : numbers){
// map.put(num,i);
// i++;
// }
// for(int j =0 ; j <numbers.length ; j++){
// int rem = target - numbers[j];
// if(map.get(rem) != null){ // ****
// ans[1] = map.get(rem);
// ans[0] = j+1;
// break;
// }
// }
// return ans;
}
}