LeetCode #167

Kiyong Lee·2022년 1월 14일
0

leetcode

목록 보기
18/20

167. input array is sorted


1. 코드

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

2. 풀이

  • start는 시작 인덱스인 0을, last는 마지막 인덱스인 len-1로 설정

  • binary search에 따라 두 개의 합이 target보다 작다면 시작인덱스를 늘려 범위를 축소 시키고

  • target보다 크다면 종료인덱스를 줄여 범위를 축소시킴

  • target과 두 개의 합이 일치한다면 인덱스에 1을 더해서 리턴
    (처음에는 인덱스를 리턴했는데, 문제에서 +1을 해서 리턴한다고 명시되어 있었음)

profile
ISTJ인 K-개발자

0개의 댓글