Two Number Sum

Given an array find two numbers that adds up to the given sum

 Input: nums = [2,7,11,15], target = 9

Output: [2,7]

Solution : 

Use java hashset first to store all elements in array then loop again through each element of array and find diff with target sum and check if difference is present in hashset


import java.util.HashSet;

class Solution{

public static void main(String[] args) {

int[] res = twoSum(new int[]{1,7,-11,15}, -10);

System.out.println(res[0]+","+res[1]);

}

    public static int[] twoSum(int[] nums, int target) {

    int[] result = new int[2];

        HashSet<Integer> numsMap = new HashSet<Integer>(nums.length);

    for(int num : nums) {

        numsMap.add(num);

        }

    for(int num : nums) {

    int nextRequiredNumber = target-num;

    if(numsMap.contains(nextRequiredNumber)) {

    result[0] = num;

    result[1] = nextRequiredNumber;

    return result;

    }

    }

    return result;

    }

}


Comments

Popular Posts