算法:JavaScript两数之和

题目

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, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].



代码

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
 //[2, 7, 11, 15]  9
 //把差存进数组,如果当前遍历数组有和差相等的值则把当前值的小标和差的下标输出来
 var twoSum = function(nums, target)  {
    let theSet = []
    for(let i = 0; i < nums.length; i++){
       if( theSet.indexOf( nums[i] )  !== -1){   //当前数和数组匹对是否存在
         return [theSet.indexOf( nums[i] ), i];     //如果有则返回当前值再数组中的位置和当前下标
       }else{
        theSet.push(target - nums[i] );//如果数组没有当前值则相减把差存进去数组  9-2=7 i=1 -- 9-7=2 i=2 -- 9-11=-2 i=3 -- 9-15=-6 i=4
       }
    }
   return [0,0];
};
 /*
var twoSum = function(nums, target) {
    var arr = [];
    var num = [];
   
   
    
    /*
    for(var i = 0;i<nums.length;i++){
        for(var j = i+1; i< nums.length; j++){
            if(nums[i] ==  target - nums[j] ){
            arr = [i,j];
            return arr;
            }
        }
        
    }
    ***
};

var twoSum = function(nums, target) {
    const diffs = new Map();
    const j = nums.findIndex((a, i) => diffs.has(target - a) || diffs.set(a, i) && 0);
    return [diffs.get(target - nums[j]), j];
};
*/

  

原文地址:https://www.cnblogs.com/pangxiaox/p/7028834.html