Skip to content

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

题目

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
Related Topics
  • 数组
  • 二分查找

  • 👍 3021
  • 👎 0
  • 解法

    时间复杂度为 O (log N) 并且是一个非降序数组,暗示需要采用二分查询方法

    采用二分法找到 target 元素后,通过 while 循环进行命中的元素的边界扩展

    py
    # leetcode submit region begin(Prohibit modification and deletion)
    class Solution:
        def searchRange(self, nums: List[int], target: int) -> List[int]:
            left = 0
            right = len(nums)
    
            while left < right:
                mid = (left + right) // 2
    
                if nums[mid] == target:
                    mid_l = mid_r = mid
                    while mid_l > 0 and nums[mid_l - 1] == target: mid_l -= 1
                    while mid_r < len(nums) - 1 and nums[mid_r + 1] == target: mid_r += 1
    
                    return [mid_l, mid_r]
    
                elif nums[mid] > target:
                    right = mid
                else:
                    left = mid + 1
    
            return [-1, -1]
    
            
    # leetcode submit region end(Prohibit modification and deletion)

    复杂度分析

    • 时间复杂度O(logN)
    • 空间复杂度O(1)