Sum Of Two

By | September 5, 2023

In the given array , return indices of 2 numbers should match the target while they add

Ex: 1

Input: nums = [1,2,7,11], target =3
Output: [0,1]
Explanation: nums[0]+nums[1]==3, we return [0,1]

So we can solve the Two Sum problem in Java using a hashmap to store the values you’ve seen so far and their indices. Here’s a Java code snippet to solve the problem:

import java.util.HashMap;

public class TwoSum {
    public int[] twoSum(int[] nums, int target) {
        // Create a hashmap to store the values and their indices
        HashMap<Integer, Integer> map = new HashMap<>();

        // Loop through the array
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];

            // If the complement is in the map, return the indices
            if (map.containsKey(complement)) {
                return new int[]{map.get(complement), i};
            }

            // Otherwise, put the current value and index into the map
            map.put(nums[i], i);
        }

        // If no solution is found, return an empty array or throw an exception
        throw new IllegalArgumentException("No two sum solution");
    }

    public static void main(String[] args) {
        TwoSum solution = new TwoSum();
        int[] nums = {1,2,7,11};
        int target = 3;
        int[] result = solution.twoSum(nums, target);
        System.out.println("Output: [" + result[0] + ", " + result[1] + "]");
    }
}

This code creates a hashmap to store the values in the nums array and their corresponding indices. It then iterates through the array, calculating the complement (the value needed to reach the target) for each element. If the complement is found in the hashmap, it means a solution has been found, and the indices are returned as the output. If no solution is found, it throws an exception or returns an empty array, depending on your preference.

Leave a Reply

Your email address will not be published. Required fields are marked *