Two Sum

Two Sum

Given:

Array of integers and a target

Output:

Find two indices where array elements sum is equals to target

Intuition:

Use HashMaps in Java to simplify the solution, I check the difference of the target-current array element value in map and then check if the map already contains a key with difference. If yes, return the index of the difference element and current element in an integer array, else put the current element into map with index i.

Solution:

{
Map<Integer, Integer> map = new HashMap<>();
for(int i=0;i<nums.length(); i++){
int curr = nums[i];
int diff = target - curr;
if(map.containsKey(diff)){
return new int[] { map.get(diff), i };
}
map.put(curr, i);
}
return null;
}

Comments