from typing import List
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
start, last = 0, len(numbers)-1
while True :
if target == numbers[start] + numbers[last] :
return [start+1, last+1]
elif target > numbers[start] + numbers[last] :
start += 1
else :
last -= 1
start
는 시작 인덱스인 0
을, last
는 마지막 인덱스인 len-1
로 설정
binary search
에 따라 두 개의 합이 target
보다 작다면 시작인덱스를 늘려 범위를 축소 시키고
target
보다 크다면 종료인덱스를 줄여 범위를 축소시킴
target
과 두 개의 합이 일치한다면 인덱스에 1
을 더해서 리턴
(처음에는 인덱스를 리턴했는데, 문제에서 +1
을 해서 리턴한다고 명시되어 있었음)