본문 바로가기

Leetcode

Leetcode 35. Search Insert Position - Binary Search

이 문제도 이진탐색을 이용하면 쉽게! 해결된다.

3분컷

 

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        # Binary Search
        low = 0
        high = len(nums) - 1
        while low <= high:
            mid = (low + high) // 2
            if nums[mid] == target:
                return mid
            elif nums[mid] < target:
                low = mid + 1
            elif nums[mid] > target:
                high = mid - 1
            
        return low

성공이다.

오늘도 한 개 했다. 뿌듯