Two Sum

Published by hitman on

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Examples :

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Input: nums = [3,2,4], target = 6
Output: [1,2]

Input: nums = [3,3], target = 6
Output: [0,1]

So the java code for the above program is:

import java.util.HashMap;

public class TwoSum {

    static int[] twoSumFn(int[] nums, int target) {
        
        HashMap<Integer,Integer> map = new HashMap<>();
        int[] ans = new int[2];

        for(int i=0;i<nums.length;i++)
        {
            int temp = target - nums[i];
            if(map.containsKey(temp))
            {
                ans[0] = i;
                ans[1] = (int)map.get(temp);
                break;
            }
            //adding to map
            map.put(nums[i],i);
        }

        return ans;

    }

    public static void main(String[] args)
    {
        int[] nums = {2,7,11,15};
        int target = 9;
        int[] ans = twoSumFn(nums,target);

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

    }

}

Time Complexity : O(n)

Space Complexity : O(n)

Practice on leetcode.


0 Comments

Leave a Reply

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