给定一个按照升序排列的整数数组 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] <= 109
nums 是一个非递减数组
-109 <= target <= 109
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ret{-1, -1};
int start = 0, end = nums.size() - 1, mid = (start + end) / 2;
while(start <= end){
mid = (start + end) / 2;
if(nums[mid] == target){
ret = {mid, mid};
for(int i = mid; i >= 0 && nums[i] == target; i--){
ret[0] = i;
}
for(int i = mid; i < nums.size() && nums[i] == target; i++){
ret[1] = i;
}
}
nums[mid] < target ? start = mid + 1 : end = mid - 1;
}
return ret;
}
};
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
start, end, mid, ret = 0, len(nums) - 1, 0, [-1, -1]
while start <= end:
mid = (int)((start + end) / 2)
if nums[mid] == target:
ret = [mid, mid]
for i in range(0, mid)[::-1]:
if nums[i] == target:
ret[0] = i
else:
break
for i in range(mid, len(nums)):
if nums[i] == target:
ret[1] = i
else:
break
if nums[mid] < target:
start = mid + 1
else:
end = mid - 1
return ret