给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
我的思维就是:数组的二重遍历,但是同一索引不同被使用两次
代码:
class Solution {
public int[] twoSum(int[] nums, int target) {
boolean flag = false;
int s[] = new int[2];
for(int i = 0; i < nums.length; i++){
flag = false;
int target1 = target - nums[i];
for(int j = 0; j < nums.length; j++){
if(j != i){
if(target1 == nums[j]){
flag = true;
s[0] = i;
s[1] = j;
}
}
if(flag)
break;
}
if(flag)
break;
}
System.out.println(s);
return s;
}
}
一个我理解的代码
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<>(nums.length * 2);
for (int i = 0; i < nums.length; i++){
int num = nums[i];
Integer index = map.get(target-num);
if (index != null){
return new int[]{index, i};
}
map.put(num, i);
}
throw new IllegalArgumentException("No two sum solution");
//return null; //cant throw exception?
}
}
自己的思考:首先使用了HashMap来存储数据,并且使用get来获取相应的索引,如果没有获取到则将该数字加入进去
就相当于从数组的0索引开始选择一个数字,用target减去选择的这个数字,看HashMap中有无这个数字,有则完成,没有的话就继续向后取值