소프트웨어에 대한 모든 것

LeetCode 풀기 - 35. Search Insert Position 본문

카테고리 없음

LeetCode 풀기 - 35. Search Insert Position

앤테바 2021. 11. 10. 07:40
반응형

35. Search Insert Position

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

 

Search Insert Position - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제)

솔루션1) - binary search

바이너리 서치를 적용해서 insert index를 찾습니다.

 

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

솔루션2) - bisect 모듈

bisect(배열 이진 분할 알고리즘) 모듈을 사용합니다.

bleect.bisect_left(a, x)는 a 배열에서 x를 삽입할 위치를 찾습니다. 삽입 위치는 기존 항목 앞(왼쪽) 입니다.

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        return bisect.bisect_left(nums, target)
반응형
Comments