Problem statement: Given an array of integers, return indices of two numbers such that they add up to a specific target.
e.g. - arr[] = { 4, 6, 5, -10, 8, 5, 20 };
target = 10
Output: [4,6] , [5,5], [-10,20]
Note: You may assume that each input would have exactly one solution, and you may not use the same element twice.
e.g. - arr[] = { 4, 6, 5, -10, 8, 5, 20 };
target = 10
Output: [4,6] , [5,5], [-10,20]
Note: You may assume that each input would have exactly one solution, and you may not use the same element twice.
- import java.util.HashMap;
- import java.util.Map;
- public class IndexOfTwoPair{
- public static void main(String[] args) {
- int a[] = { 4, 6, 5, -10, 8, 5, 20 };
- int n = 10;
- int idx[] = indexOfTwoSum(a, n);
- for (int i : idx) {
- System.out.print(i + " ");
- }
- }
- public static int[] indexOfTwoSum(int nums[], int target) {
- // array to return the result
- int arr[] = new int[2];
- // map for num and index pair
- Map<Integer, Integer> map = new HashMap<Integer, Integer>();
- // scan the array element
- for (int i = 0; i < nums.length; i++) {
- // check if map has an element which is equal to difference
- // between target and current element
- Integer val = map.get(target - nums[i]);
- if (val == null) {
- // no match found, add current element & index to map
- map.put(nums[i], i);
- } else {
- // match found, update the index values
- arr[0] = val;
- arr[1] = i;
- }
- }
- return arr;
- }
- }
Output:
3 6
No comments:
Post a Comment