본문 바로가기

두두의 알고리즘/문제

[이분탐색] 릿코드 Medium 34 'Find First and Last Position of Element in Sorted Array' (Python)

728x90

<문제 링크>

https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

 

Find First and Last Position of Element in Sorted Array - 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. 파이썬의 bisect 라이브러리를 활용

2. target이 nums에 있다면 정답을 반환하고 없으면 [-1,-1]을 반환함

 

<코드>

from bisect import bisect_left, bisect_right

class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        
        if target in nums:
            a = bisect_left(nums,target)
            b = bisect_right(nums,target)
            
            return [a,b-1]
        
        return [-1,-1]