1. 程式人生 > >python leetcode 34. Find First and Last Position of Element in Sorted Array

python leetcode 34. Find First and Last Position of Element in Sorted Array

二分定位,再前後遍歷

class Solution:
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if nums==[]:
            return [-1,-1]
        p = 0
        q = len(nums)
        
        while p < q:
            mid =
(p+q)//2 if nums[mid] == target: break elif nums[mid] > target: q = mid else: p = mid + 1 if p>=q: return [-1,-1] l = mid r = mid while l>=0 and nums[l] == target:
l-=1 while r<len(nums) and nums[r] == target: r+=1 return [l+1,r-1]