알고리즘

leetcode 35 - Search Insert Position

Jaymyong66 2023. 5. 28. 20:33

https://leetcode.com/problems/search-insert-position/description/

 

Search Insert Position - LeetCode

Can you solve this real interview question? Search Insert Position - Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must w

leetcode.com

삽입 정렬 구현 문제.

log(n)으로 풀어야 한다.

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