难度:简单
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
Java解法:
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> hashmap=new HashMap<>(nums.length-1);
hashmap.put(nums[0],0);
for(int i=1;i<nums.length;i++){
int another=target-nums[i];
if(hashmap.containsKey(another)){
return new int[]{hashmap.get(another),i};
}else{
hashmap.put(nums[i],i);
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
JavaScript解法:
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
var numstore={};
numstore[nums[0]]=0;
// console.log(numstore);{ '2': 0 }
for(var i=1;i<nums.length;i++){
var another=target-nums[i];
if(numstore[another]!==undefined){
return [numstore[another],i];
}else{
numstore[nums[i]]=i;
}
}
};
思路:
1.创建一个map
2.用for循环遍历nums数组
3.算出another值(用target减去nums[i])
4.检查map里有没有这个数