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

66 阅读1分钟

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

给你一个按照非递减顺序排列的整数数组 nums,和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。如果数组中不存在目标值 target,返回 [-1, -1]。你必须设计并实现时间复杂度为 O(log n) 的算法解决此问题。

  示例 1:

输入: nums = [5,7,7,8,8,10], target = 8
输出: [3,4]

示例 2:

输入: nums = [5,7,7,8,8,10], target = 6
输出: [-1,-1]

示例 3:

输入: nums = [], target = 0
输出: [-1,-1]

提示:

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • nums 是一个非递减数组
  • -10^9 <= target <= 10^9

代码

1.遍历

def searchRange(nums , target) :     
    # 1.index + 遍历
    res = [-1,-1]
    if not nums:
        return res 

    if target in nums:
        res[0] = nums.index(target)
    else:
        return res

    for i in range(len(nums) - 1 , res[0] - 1, -1):
        #倒着来
        if nums[i] == target:
            res[1] = i
            return res
    return res

2.二分

def searchRange(nums, target):
    # 2.二分
    def lower_bound(nums,target):
        i = 0
        j = len(nums) - 1
        while i <= j:
            mid = (i + j) // 2
            if nums[mid] < target:
                i = mid + 1
            else:
                j = mid - 1
        return i
    if not nums:
        return [-1,-1]
    left = lower_bound(nums,target)
    if left == len(nums) or nums[left] != target:
        return [-1,-1]

    # 流程到这里说明数组中有tatget
    right = lower_bound(nums, target + 1) - 1 # 整数,找到第一个比target大的第一个数,后面那个数就是target

    return [left , right]