Two sum solution in Java .
Question : Given an array of integers nums and an integer target, return
indices of the two numbers such that they add up to target. You may assume
that each input would have exactly one solution, and you may not use the same
element twice. You can return the answer in any order.
Input : nums =
[2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9,
we return [0, 1].
import java.util.*;
class TwoSum
{
static int[] calculate(int[] arr , int target) {
Map<Integer,Integer> map = new HashMap<>();
for(int i=0;i<arr.length;i++) {
int remain = target - arr[i];
if(map.containsKey(remain)) {
return new int[] {map.get(remain),i};
}
map.put(arr[i],i);
// System.out.println(map);
}
throw new IllegalArgumentException("No two sum solution");
}
public static void main(String[] args) {
try
{
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] arr = new int[n];
int target = input.nextInt();
for(int i=0;i<n;i++) {
arr[i] = input.nextInt();
}
int ans[] = calculate(arr,target);
System.out.println("Index = "+ans[0]+" : "+ans[1]);
}
catch(Exception e){
return;
}
}
}
Output :
5 7
1 2 3 4 5
Index = 2 : 3