Given an array of integers, return indices of the two numbers such
that they add up to a specific target.htmlYou may assume that each input would have exactly one solution, and
you may not use the same element twice.codeExample:htm
Given nums = [2, 7, 11, 15], target = 9,blog
Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].排序
leetcode的oj就是比X客的牛逼,console.log()沒有註釋,照樣ac。
原本是easy的題目,最近看灣區那邊的面經總是看到nSum的字樣,索性就把這個系列的都作一遍吧。ci
思路就是保存下index,排序,而後兩邊往中間遍歷(這個思路是以前作過哪道題來着)element
/** * @param {number[]} nums * @param {number} target * @return {number[]} * 其餘解題思路:http://www.cnblogs.com/grandyang/p/4130379.htmls */ var twoSum = function(nums, target) { let newo = nums.map(function(item,index) { let t = {}; // console.log(item,index); t.index = index; t.value = item; // console.log(newo); return t; }); //console.log(newo); newo.sort((a ,b) => a.value-b.value || -1); //console.log(newo); // console.log(nums); let len = newo.length; //console.log(len); let i = 0,j=len-1; let ans = []; while(i<j) { if(newo[i].value+newo[j].value=== target) { ans.push(newo[i].index,newo[j].index); i++; j--; }else if(newo[i].value+newo[j].value>target) { j--; }else if(newo[i].value+newo[j].value<target) { i++; } // console.log(nums); } return ans; } console.log(twoSum([3, 2, 4], 6));;