For example, the target is 9 and the first number in the int array is 2. 9 - 2 = 7, so 7 is the complement.
Check if we have seen the complement before.
If no, add the number as the key in the map, and the index i as the value (the index i is the value because the solution wants us to return the index for the answer). The map is used to keep track of previously seen numbers and if the current number has a complement that we have seen already and is currently in our map, we can stop.
If yes (as in the case when the current interation gives us the number 7), this means we have seen the complement 2 before during our iteration, and the complement of 7 in order to add up to 9 is 2. Thus, we found the answer, stop the loop, and the answer will be the current iteration index of i, and the value we get corresponding to the key of the complement 2.
import java.util.*;
public class HelloWorld{
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> mapOfAnswers = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++)
{
int complement = target - nums[i];
if (mapOfAnswers.containsKey(complement))
{
return new int[] {mapOfAnswers.get(complement), i};
}
mapOfAnswers.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
public static void main(String []args){
int[] data = new int[]{2, 7, 11, 15};
System.out.println(Arrays.toString(twoSum(data, 9)));
}
}
No comments:
Post a Comment