Quick actions

cmd+k|ctrl+k

Navigation

Languages

Two Sum

Snippet info

Language

Java

Visibility

public

Author

shraddharao-

Created

2024-02-27T19:52:10.53533Z

Updated

2024-02-27T19:52:10.53533Z

import java.util.*;

class Main {
    /*
    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.

    nums = [2, 7, 11, 15]
    target = 9
    output = [0, 1]


    // create a HashMap to store the numbers 
    // iterate through the array and check if the complement exits
    // return the current element, otherwise its index 
    //if solution found, return empty array
    */
    
    // time and space : o(n)
    
    public static int[] twoSum(int[]nums, int target){
        HashMap<Integer, Integer>map = new HashMap<>();
        
        for (int i=0; i<nums.length; i++){
            int complement = target -nums[i];
            if (map.containsKey(complement)){
                return new int[]{map.get(complement), i};
            }
            map.put(nums[i], i);
        }
        return new int[0];
    }
    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
        int target = 9;
        
        int[] result = twoSum(nums, target);
        System.out.print(Arrays.toString(result));
    }
}
INFO