LeetCode 题解工作台
在排序数组中查找元素的第一个和最后一个位置
给你一个按照非递减顺序排列的整数数组 nums ,和一个目标值 target 。请你找出给定目标值在数组中的开始位置和结束位置。 如果数组中不存在目标值 target ,返回 [-1, -1] 。 你必须设计并实现时间复杂度为 O(log n) 的算法解决此问题。 示例 1: 输入: nums = …
2
题型
10
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
我们可以进行两次二分查找,分别查找出左边界和右边界。 时间复杂度 $O(\log n)$,其中 是数组 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给你一个按照非递减顺序排列的整数数组 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 <= 105-109 <= nums[i] <= 109nums是一个非递减数组-109 <= target <= 109
解题思路
方法一:二分查找
我们可以进行两次二分查找,分别查找出左边界和右边界。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
l = bisect_left(nums, target)
r = bisect_left(nums, target + 1)
return [-1, -1] if l == r else [l, r - 1]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(log n) because each boundary search halves the search space. Space complexity is O(1) since no extra structures are used; only pointers and indices are maintained. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate identifies both leftmost and rightmost positions using separate searches.
- question_mark
Listen for correct pointer movement logic to handle duplicates without scanning the entire array.
- question_mark
Expect clarification on edge cases, such as empty arrays or targets at array boundaries.
常见陷阱
外企场景- error
Using a single binary search and assuming the first match is the left boundary.
- error
Incorrect pointer updates that skip valid duplicates, causing wrong last position.
- error
Neglecting validation after search, which can return indices when target is absent.
进阶变体
外企场景- arrow_right_alt
Find the count of target occurrences using the same binary search boundaries approach.
- arrow_right_alt
Return all ranges of multiple target values efficiently in one pass.
- arrow_right_alt
Handle rotated sorted arrays while still identifying first and last positions with modified binary search.