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

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

解法一:二分

naive方法,先用二分找target,找到向两端扩张,看左右有没有相等的数。

class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        n = len(nums)
        l = 0
        h = n-1
        res = []
        find = -1  #找到的数下标,初始为-1
        while l <= h:  #二分查找
            mid = (l+h) // 2
            if nums[mid] < target:
                l = mid + 1
            elif nums[mid] > target:
                h = mid - 1
            else:  #若找到,用find记录位置,并跳出
                find = mid
                break
        if find == -1:  #若find仍为-1,说明没找到
            return [-1, -1]
        #向左右扩张
        left = right = find
        while left-1 >= 0 and nums[left-1] == nums[left]:
            left -= 1
        res.append(left)
        while right+1 < n and nums[right+1] == nums[right]:
            right += 1
        res.append(right)
        return res

解法二:二分找左右边界

修改二分查找的条件,可以分别找到连续个等于tar的数的最左端和最右端。

最后更新于