1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution.

Solution:
public class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> m = new HashMap<>();
        int[] rts = {0,0};
        for(int i = 0; i<nums.length ;i++){
            if(m.containsKey(nums[i])){
                rts[0] = m.get(nums[i]);
                rts[1] = i;
                return rts;
            }
            else{
                m.put(target-nums[i], i);
            }
        }
         return rts;
    }
}

results matching ""

    No results matching ""