Scribbling

35. Search Insert Position 본문

Computer Science/Coding Test

35. Search Insert Position

focalpoint 2021. 9. 8. 21:52

Binary Search 살짝만 바꿔주자

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

'Computer Science > Coding Test' 카테고리의 다른 글

33. Search in Rotated Sorted Array  (0) 2021.09.11
LeetCode: 31. Next Permutation  (0) 2021.09.09
LeetCode: 49. Group Anagrams  (0) 2021.09.08
LeetCode: 41. First Missing Positive  (0) 2021.09.08
LeetCode: 47. Permutations II  (0) 2021.09.07