Java Solution - LeetCode Problem 1 Two Sum

Java Solution - LeetCode Problem 1 Two Sum

Problem Description:

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

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

Link to the problem

Solution:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        //map to store visited numbers along with their index
        HashMap<Integer,Integer> map = new HashMap<>();
        for (int i=0; i<nums.length; i++) {
            int requiredNum = target - nums[I];
            if(map.containsKey(requiredNum)) {
                //return the current index and the index from the map
                return new int[] {map.get(requiredNum), i};
            } else {
                map.put(nums[i], i);
            }
        }
        return null;
    }
}