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

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

Medium

10708294Add to ListShare

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

If target is not found in the array, return [-1, -1].

You must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

Example 3:

Input: nums = [], target = 0
Output: [-1,-1]

Constraints:

  • 0 <= nums.length <= 105
  • -109 <= nums[i] <= 109
  • nums is a non-decreasing array.
  • -109 <= target <= 109
class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        """
        assert Solution().searchRange([0, 0, 0, 1, 2, 3], 0) == [0, 2]
        assert Solution().searchRange([2, 2], 3) == [-1, -1]
        assert Solution().searchRange([2, 2, 2], 2) == [0, 2]
        assert Solution().searchRange([1, 2, 2, 2, 4], 2) == [1, 3]
        assert Solution().searchRange([5, 7, 7, 8, 8, 10], 8) == [3, 4]
        assert Solution().searchRange([5, 7, 7, 8, 8, 10], 6) == [-1, -1]
        assert Solution().searchRange([], 8) == [-1, -1]

        # 87ms
        if target not in nums: return [-1,-1]
        l = bisect_left(nums,target)
        r = bisect_right(nums,target)
        return [l,r-1]

        解题思路:二分查找最左和最右  
        时间复杂度:O(logn)  99ms
        """
        if nums is None or len(nums) <= 0:
            return [-1, -1]

        # 二分查找最左
        def findL(l: int, r: int) -> int:
            if l >= r:
                if l < len(nums) and nums[l] == target:
                    return l
                return -1

            mid = int((l + r) / 2)
            if nums[mid] >= target:
                # 保留mid,接着往左寻
                return findL(l, mid)
            return findL(mid + 1, r)

        # 二分查找最右
        def findR(l: int, r: int) -> int:
            if l >= r:
                if l < len(nums) and nums[l] == target:
                    return l
                return -1

            mid = int((l + r) / 2)
            if nums[mid] == target:
                if mid + 1 < len(nums) and nums[mid + 1] == target:
                    # 右边还有
                    return findR(mid + 1, r)
                return mid
            elif nums[mid] < target:
                return findR(mid + 1, r)
            return findR(l, mid - 1)

        # 拆开会比直接返回[findL(0, len(nums)),findR(0, len(nums))]快
        l = findL(0, len(nums))
        r = findR(0, len(nums))
        return [l, r]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值