Find First and Last Position of Element in Sorted Array
Given an array of integers
numssorted in ascending order, find the starting and ending position of a giventargetvalue.Your algorithm’s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return
[-1, -1].
Example 1
1 | Input: nums = [5,7,7,8,8,10], target = 8 |
Example 2
1 | Input: nums = [5,7,7,8,8,10], target = 6 |
解题思路
分别用二分法找出目标的左边界和右边界。找左边界时,若 nums[mid]>=target,二分搜索的上界 r=mid-1,否则二分搜索的下界 l=mid+1,最后返回 r+1。找右边界时,若 nums[mid]<=target,二分搜索的下界 l=mid+1,否则二分搜搜的上界 r=mid-1,最后返回 l-1。若左边界大于右边界,说明 nums 中不存在target,返回 [-1,-1];否则,返回左右边界。
复杂度分析
- 时间复杂度:$O(logn)$。
- 空间复杂度:$O(1)$。
代码
1 | class Solution { |