Started With Leetcode- Array- Q1 Two Sum

Pranjal Sailwal - May 15 - - Dev Community
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> numMap = new HashMap<>();
        int n = nums.length;
//Building Hash 
        for (int i = 0; i < n; i++) {
            numMap.put(nums[i], i);
        }
//Finding complement
        for (int i = 0; i < n; i++) {
            int complement = target - nums[i];
            if (numMap.containsKey(complement) && numMap.get(complement) != i) {
                return new int[]{i, numMap.get(complement)};
            }
        }
//for no solution
        return new int[]{};
    }
}
Enter fullscreen mode Exit fullscreen mode

Open to updates and suggestions.

. . . . . . . . . .