I'm working on this problem in leetcode by using .map method, but somehow it returns undefined. Could anybody please explain why this happened? I read the doc, and it says that .map usually returns an array.
var twoSum = function (nums, target) {
for (let i = 0; i < nums.length; i++){
const num = nums[i];
nums.slice(i+1).map((element) => {
if (num + element === target){
return [i, nums.indexOf(element, i+1)];
}
});
}
}
Just to add , this is like a starter example where we can use two pointer pattern.
First setup to apply two pointer is to sort the array.
Then take two pointers first one starting at 0 index and second one starting at last index
Traverse the loop and check the target and increment and decrement the pointers accordingly
var twoSum = function(nums, target) {
nums.sort((a,b) => a-b )
var startingIndex = 0
var lastIndex = nums.length-1;
while(startingIndex<lastIndex){
if(nums[startingIndex] + nums[lastIndex] === target){
console.log(nums[startingIndex], nums[lastIndex])
startingIndex++;
lastIndex--;
}
if(nums[startingIndex] + nums[lastIndex] < target){
startingIndex++;
}
if(nums[startingIndex] + nums[lastIndex] > target){
lastIndex--;
}
}
};
console.log(twoSum([2, 7, 20, 13, 15], 33));
You can use Map here to achieve the result efficiently
var twoSum = function(nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; ++i) {
if (map.has(nums[i])) return [map.get(nums[i]), i];
else map.set(target - nums[i], i);
}
};
console.log(twoSum([2, 7, 11, 15], 9));