파비의 매일매일 공부기록

2023.02.20 Today's Challenge 본문

Problem Solving/LeetCode

2023.02.20 Today's Challenge

fabichoi 2023. 2. 20. 23:45

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

 

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

이진 탐색을 쓰면 되는 문제.
근데 나는 못품 =_= 

그리고 솔루션 봤는데.. 허망
제일 간단하게는 bisect 활용하면 됨.

물논 이진 탐색은 개념을 알긴 아는데.. 마지막 return 조건이 애매한 것 같아서 손도 안댔다 ㅠ_ㅠ
솔루션만 복사해서 푸는게 효과가 있는가!!! 라고 자문해보지만
그래도 어쨌든 하긴 했다. 

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        s, e = 0, len(nums) - 1
        while s <= e:
            mid = (s+e) // 2
            if nums[mid] == target:
                return mid
            elif nums[mid] > target:
                e = mid - 1
            else:
                s = mid + 1
        return e + 1
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.02.22 Today's Challenge  (0) 2023.02.22
2023.02.21 Today's Challenge  (0) 2023.02.21
2023.02.19 Today's Challenge  (0) 2023.02.19
2023.02.18 Today's Challenge  (0) 2023.02.18
2023.02.17 Today's Challenge  (0) 2023.02.17
Comments