Wednesday, April 3, 2019

Two Sum [find a pair of index or two sum of index in a list]

Problem statement:
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.

Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

import java.util.HashMap;
public class Solutions {
    public static void main(String args[]) {
        int nums[] = {2, 7, 11, 15};
        int target = 9;
        int idx[] = twoSum(nums, target);
        for (int index : idx) {
            System.out.print(index + " ");
        }
    }

    public static int[] twoSum(int nums[], int target) {
        HashMap m = new HashMap();
        int arr[] = new int[2];

        for (int i = 0; i < nums.length; i++) {
            Integer val = (Integer) m.get(target - nums[i]);
            if (val == null) {
                m.put(nums[i], i);
            } else {
                arr[0] = val;
                arr[1] = i;
            }
        }
        return arr;
    }
}
Output:    [0,1]
Expected: [0,1]

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...