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, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
tag: array, hash table
method 1
two-pass hash table 第一边遍历,将每一个数放进map中,第二次遍历时,遍历map中是否存在target-nums[i]有就取索引直接返回
public int[] twoSum(int[] nums, int target) {
Set<Integer> set = new HashSet<>();
int[] res = new int[2];
int anotherNum = 0;
for (int i = 0; i < nums.length; i++) {
if (set.contains(target-nums[i])){
res[1] = i;
anotherNum = target-nums[i];
break;
}
set.add(nums[i]);
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] == anotherNum){
res[0] = i;
break;
}
}
return res;
}
method 2
one-pass hash table, 其实一次遍历就够,每次遍历的时候检查map中是否有target-nums[i]的数,没有就放进map中,总会找到的
public int[] twoSum2(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");
}