Node.js examples for Array:Array Value
Given an array of integers, return indices of the two numbers such that they add up to a specific target
/*/*w w w. j a v a2 s .co m*/ 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]. */ var twoSum = function(nums, target) { for(let i=0; i<nums.length; i++) { for(let k=i+1; k<nums.length; k++) { if ((nums[i] + nums[k]) === target) { return[i, k]; } } } return "No matches"; }; //Sam as above but it can have multiple correct answers function twoSum(nums, target) { let temp = []; for(let i=0; i<nums.length; i++) { if ((nums[i] + nums[i+1]) === target) { temp.push([i, i+1]); } else { for (let k=0; k < nums.length; k++) { if(nums[i] + nums[k] === 0) { temp.push([i, k]); } } } } return temp; }