Started With Leetcode- Array- Q1 Two Sum

sailwalpranjal

Pranjal Sailwal

Posted on May 15, 2024

Started With Leetcode- Array- Q1 Two Sum
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.

πŸ’– πŸ’ͺ πŸ™… 🚩
sailwalpranjal
Pranjal Sailwal

Posted on May 15, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related