Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Monday, May 2, 2022

Two Sum Java Solution


Problem:

Given an array of integers numbers 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.
 

Example 1:

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

Approach: 

Maintain Map with Index and handle case for duplicity so that we are not taking same element again

 

Solution:

 public int[] twoSum(int[] nums, int target) {
        int a[] = new int[2];
        HashMap<Integer, Integer> set = new HashMap<>();
        for(int i =0;i<nums.length; ++i) {
            set.put(nums[i], i);
        }
        for(int i =0;i<nums.length; ++i) {
            if(set.containsKey(target-nums[i]) && i != set.get(target-nums[i]))
            {
             a[0] = i;
            a[1] = set.get(target-nums[i]);
                return a;
            }
        }
        return a;
    }

0 Comments:

Post a Comment

Stats