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.
Example: Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
This question has a small trap should pay attention, say the following solution
public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
int[] res = new int[2];
for(int i=0; i<nums.length ;i++){
map.put(nums[i], i);
}
for(int i=0; i< nums.length; i++){
int t = target - nums[i];
if(map.containsKey(t)){
res[0] = i;
res[1] = map.get(t);
}
}
return res;
}
}
for this specific case:
[0,4,3,0], 0, ===> the above solution gives [3,3], not [0,3]. to fix this bug.
public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
int[] res = new int[2];
for(int i=0; i< nums.length; i++){
if(map.get(nums[i]) != null){
res[0] = map.get(nums[i]);
res[1] = i;
return res;
}else{
map.put(target-nums[i], i); // cross reference the key and pos.
}
}
return res;
}
}