In other words, understand that if arr[pointer_one]
< target-arr[pointer_two]
, it means we should move forward on pointer_one
to get closer to where we want to be in magnitude.
This is what it looks like all put together:
xxxxxxxxxx
14
var twoSum = function (arr, target) {
for (let i = 0, j = arr.length - 1; i < j; ) {
let sum = arr[i] + arr[j];
if (sum === target) {
return [i + 1, j + 1];
} else if (sum < target) {
i++;
} else {
j--;
}
}
};
​
console.log(twoSum([1, 3, 4, 8, 9], 11));
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment