Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
var twoSum = function(numbers, target) {
let result = [];
for(let i=0; i < numbers.length-1; i++) {
for(let j=i+1; j < numbers.length; j++){
let sum = numbers[i] + numbers[j];
if ( sum === target ){
result.push(i+1);
result.push(j+1);
}
}
}
return result;
};
// 리팩토링
var twoSum = function(numbers, target) {
let start = 0;
let end = numbers.length-1;
while(start < end){
let sum = numbers[start] + numbers[end];
if(sum === target){
return [ start+1, end+1 ]
}
else if ( sum < target ){
start++;
}
else {
end--;
}
}
};