Topic Address: 1. Two Sum
Referring to a third solution which
I had a doubt: Why take complement
as key
?
General key-value pairs, then complement
it should be value
, and i
is the key
son.
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
But if we look inside the key and value exchange, what will happen?
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(i)) {
return new int[] { i , map.get(complement)};
}
map.put( i ,nums[i]);
}
throw new IllegalArgumentException("No two sum solution");
}
}
error! Because the if(map.containsKey(i))
inside i
is 0,1,2, we have to compare that num[]
number inside (Figure: To compare that 1,3,11,8) instead i
.
So we want to complement
be askey