Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package com.omt.learn.algo; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.TreeMap; public class IndicesOfNumbers { public static void main(String[] args) { int[] a = { 2, 7, 11, 15, 17, 20 }; int target = 9; for(int i : twoSum(a, target)) { System.out.println(i); } } public static int[] twoSum(int[] nums, int target) { int[] indexList = new int[2]; Map<Integer, Integer> dataMap = new TreeMap<>(); for (int i = 0; i < nums.length; i++) { if (dataMap.containsKey(target - nums[i])) { System.out.println("Two indices are :[" + dataMap.get(target - nums[i]) + "," + i + "]"); indexList[0] = dataMap.get(target - nums[i]); indexList[1] = i; break; } dataMap.put(nums[i], i); } return indexList; } } |