Given an array of integers and a target value, find two numbers in the array that sum to the target value.
You can assume that each input corresponds to only one answer, and that the same elements cannot be reused.
Given nums = [2, 7, 11, 15], target = 9 because nums[0] + nums[1] = 2 + 7 = 9 So return [0, 1]
import java.util.HashMap; import java.util.Map; public class TwoSum { public static void tosum(int[] nums, int target){ Map<Integer, Integer> hashmap = new HashMap<>(); for(int i=0;i<nums.length;i++){ for(int j = i+1;j<nums.length;j++) { if ( nums[i] + nums[j] == target) { hashmap.put(i, j); } } } System.out.println(hashmap); } public static void main(String[] args) { // TODO Auto-generated method stub int[] nums = {3,2,4,1,5}; int target = 6; tosum(nums, target); } }