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].
leetcode的oj就是比X客的牛逼,console.log()没有注释,照样ac。
本来是easy的题目,最近看湾区那边的面经老是看到nSum的字样,索性就把这个系列的都做一遍吧。
思路就是保存下index,排序,然后两边往中间遍历(这个思路是之前做过哪道题来着)
/**
* @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));;