34.查找排序数组元素的第一个位置和最后一个位置

class Solution(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """

        n = len(nums)
        if n<1:
            return [-1,-1]
        left = 0
        right = n -1
        while left < right:
            mid = (left+right)//2
            if nums[mid] target:
                right = mid - 1
            else:
                begin = mid
                end = mid
                while begin-1>=0 and nums[begin-1]==target:
                    begin -= 1
                while end+1 <= (n-1) and nums[end+1]==target:
                    end +=1
                return[begin,end]
        if nums[left]==target:
            return [left,right]
        else:
            return[-1,-1]

你可能感兴趣的:(34.查找排序数组元素的第一个位置和最后一个位置)