算法:JavaScript兩數之和
阿新 • • 發佈:2017-06-16
number 遍歷 sam arr use hat *** 和數 find
題目
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]; }; */
算法:JavaScript兩數之和