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].题目给出的限制条件是:每个输入的数组都恰好只有唯一一个解。
有两种解决方法:
1 朴素解法:index1指向数组第一个元素,然后用index2从数组第一个元素开始,遍历数组,知道找到nums[index1] + nums[index2] = target。如果找不到index2,则index++;然后index2 =0;继续遍历数组,直到index1= nums.length,退出。
这种解法时间复杂度是O(n^2);太慢
2使用HashMap<Integer ,Integer>。将HashMap的key设定为target-nums[i],value设定为 i 。读取nums[i] ,然后只要判断target-nums[ i ]是否在HashMap中即可,若在,则返回 i 和 map.get(target - nums[ i]);
public int[] twoSum(int[] nums, int target){
int len = nums.length;
int[] result = new int[2];
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0;i<n;i++){
if(map.containsKey(nums[i])){
result[0] = map.get(nums[i]); //得到nums[i] 对应的在nums中的index
result[1] = i;//target-nums[i]对应的index2
break;
}
else{
map.put(target - nums[i], i);//map中key是target-nums[i],value是 i
}
}
return result;
}
思考:
如果数组中有多个值满足nums[i] + nums[j] = target,那么result[ ]该设置为多大长度?
若设置为nums.length,则result[ ]中未使用的部分值都为0,返回的result不正确。在新建一个数组,长度为result中去掉后面的0之后的长度,将result中的值copy到新数组 。