英文
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]. |
中文
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
1.穷举法
运用两层for嵌套,让每两个数相加,得到目标值后返回数组下标。
var twoSum = function(nums, target) {
var len=nums.length;
for(var i=0;i<len;i++){
for(var j=i+1;j<len;j++){
if(target==nums[i]+nums[j]){
return [i,j];
}
}
}
};
2.Hash的办法
在所给数组中查找依次查找与当前值所对应的目标值是否存在,如果存在则记录当前index值。
var twoSum = function(nums, target) {
// 用于记录数组nums的长度
const length = nums.length;
// 实例化一个Map对象
let hash = new Map();
let index = 0;
for (index = 0; index < length; index++) {
// 设置 hashMap 的 <key, value>,用于后面比较取值
hash.set(nums[index], index);
}
// 遍历数组中的每一个数,求出另一个与其相加可以满足条件的数的值,存储在 @param numToFind 中
let numToFind;
for( index = 0; index < length; index++) {
numToFind = target - nums[index];
// 查询 hashMap 中对应的值是否有对应的index,而且不能是当前数的下标(防止出现 3 + 3 = 6,但数组nums中只有一个3这样的情况)
if (hash.has(numToFind) && index !== hash.get(numToFind)) {
return [index, hash.get(numToFind)];
}
}
};