35. Search Insert Position

치즈말랑이·2021년 10월 6일
0
post-thumbnail

원리는 매번 같은 binary search인데 문제는 다 달라지네..
target이 array 안에 있으면 기본적인 binary 알고리즘을 사용하면 되는데, 값이 없을 경우에는 모르겠어서 discuss를 봤다..

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        l,r=0,len(nums)-1
        while l<=r:
            m=int((l+r)//2)
            if nums[m] == target:
                return m
            elif nums[m] < target:
                l=m+1
            else:
                r=m-1
        return l

while l<=r가 아닐 경우에 return l이 신기한데..
문제에 나온 예시를 가지고 직접 알고리즘을 계산해봤을때 output이 제대로 도출된다.
이런걸 대체 어떻게 생각해내는건지 모르겠다. 경이롭다.
알고리즘을 직접 계산해본 후에 짜야하는건지,

profile
공부일기

0개의 댓글

관련 채용 정보