LeetCode第一题
1. 两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 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) {
int data[]=new int[2];
for(int i=0;i
for(int j=i+1;j
if(nums[i]+nums[j]==target){
data[0]=i;
data[1]=j;
}
}
}
return data;
}
}
解法二:map集合
解题思路:
1.创建一个map
2.for循环遍历nums数组
3.用target减nums[i],以计算哪个数能跟当前的数字相加得到target
4.检查map里有没有这个数,如果有则返回结果,如果没有则把nums[i]当做key,i当做value放入map中
思考:为什么要把nums[i]当做key,i当做value放入map中
原因:map集合中检查值操作map.has()检查的是map里面有没有包含哪个key,而不是包含哪个value
写法一:
class Solution {
public int[] twoSum(int[] nums, int target) {
Map map=new HashMap<>();
for(int i=0;i
int temp = target-nums[i];
if(map.containsKey(temp)){
return new int[] {map.get(temp),i};//必须返回一个数组类型
}else{//没有找到则把当前值存入key,把当前index值存入value
map.put(nums[i],i);
}
}
return new int[]{-1,-1}; //必须返回一个数组类型
}
}
写法二:
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res=new int[2];
if(nums.length == 0 || nums==null || nums.length<=1){return res;}
else{
Map map=new HashMap();
for(int i=0;i
int num=nums[i];
int temp = target-nums[i];
if(map.containsKey(temp)){//map集合中找到key值和temp值匹配
res[0]=map.get(temp);
res[1]=i;
return res;//必须返回一个数组类型
}else{//没有找到则把当前值存入key,把当前index值存入value
map.put(num,i);
}
}
}
return res; //必须返回一个数组类型
}
}