两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]
第一种解法:暴力解法
class Solution {
public int[] twoSum(int[] nums, int target) {
//利用两层嵌套循环
for(int i=0;i<nums.length-1;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i]+nums[j] == target)
return new int[]{i,j};
}
}
return new int[]{0,0};
}
}
第二种解法:利用hashmap键值对
class Solution {
public int[] twoSum(int[] nums, int target) {
//定义一个hashmap,用来储存数组中元素值及其下标,即key是元素值,value是下标
Map<Integer,Integer> hashmap = new HashMap<Integer,Integer>();
//遍历循环,如果在hashmap中存在key为target-nums[i]的数,那么返回这两个数的小标组成的数组
for(int i=0;i<nums.length;i++){
if(hashmap.containsKey(target-nums[i]))
return new int[]{hashmap.get(target-nums[i]),i};
//否则将nums[i],i添加进hashmap中
hashmap.put(nums[i],i);
}
//如果遍历完后啥也没有,返回一个空数组
return new int[0];
}
}