Software engineer

LC-Two Sum

LC-Two Sum

Two Sum

Question

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

Input: nums = [2,7,11,15], target = 9

Output: [0,1]

Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map =new HashMap<>();
       for(int i=0;i<nums.length;i++){
           int num=nums[i];
           int res=target-nums[i];
           if(map.containsKey(res)){
               return new int[] {map.get(res),i};

           }map.put(num, i);
       }return null;
    }
}
comments powered by Disqus