[알고리즘] 167. Two Sum II - Input array is sorted

프최's log·2020년 12월 29일
0

study

목록 보기
59/59

문제 (Easy)

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.

제한사항

  • Your returned answers (both index1 and index2) are not zero-based.
  • You may assume that each input would have exactly one solution and you may not use the same element twice.

알고리즘

  1. 각 요소를 더하고
  2. 그 값이 target과 동일하면
  3. 더한 두개의 인자의 'index' 값을 output 배열로 내보낸다.

구현

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--;
    }
  }

};
profile
차곡차곡 쌓아가는 나의 개발 기록

0개의 댓글