Approach
The idea to solve this problem is to use a hashmap.
- For each element put the number and its index in the hashmap
- Difference = Target – current_num;
- if we find a difference in the hashmap, We get the solution
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> prevMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
int diff = target - num;
if (prevMap.containsKey(diff)) {
return new int[] { prevMap.get(diff), i };
}
prevMap.put(num, i);
}
return new int[] {};
}