1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| * @param {number[]} nums * @param {number} target * @return {number[]} */
function twoSum(nums, target){ for(var i = 0, len = nums.length; i < len; i++){ if(target >= nums[i]){ for(var j = i; j < len; j++){ if(target === nums[i] + nums[j]){ return [i, j]; } } } } return []; };
function twoSum(nums, target){ var index; for(var i = 0, len = nums.length; i < len; i++){ if(target >= nums[i]){ index = nums.indexOf(target - nums[i]); if(index !== -1 && index > i){ return [i, index]; } } } return []; };
function twoSum(nums, target){ var temp = {}; var res = []; for(var i = 0, len = nums.length; i < len; i++){ if(target >= nums[i]){ if(temp[target - nums[i]] !== undefined){ return [temp[target - nums[i]], i]; }else { temp[nums[i]] = i; } } }
return []; };
console.log(twoSum([1, 2, 3, 4, 5, 6, 7], 9));
|