给你一个按照非递减顺序排列的整数数组 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/problems/find-first-and-last-position-of-element-in-sorted-array
代码如下
class Solution {
int solveleft(vector<int>&nums,int target)
{
int left=0;
int right=nums.size()-1;
int leftbinary=-2;
while(left<=right){
int mid=left+((right-left)/2);
if(nums[mid]>=target)
{
right=mid-1;
leftbinary=right;
}
else{
left=mid+1;
}
}
return leftbinary;
}
int solveright(vector<int>&nums,int target)
{
int left=0;
int right=nums.size()-1;
int rightbinary=-2;
while(left<=right){
int mid=left+((right-left)/2);
if(nums[mid]>target)
{
right=mid-1;
}
else{
left=mid+1;
rightbinary=left;
}
}
return rightbinary;
}
public:
vector<int> searchRange(vector<int>& nums, int target) {
int rightbinary=solveright(nums,target);
int leftbinary=solveleft(nums,target);
if(rightbinary == -2||leftbinary==-2) return {-1,-1};
if(rightbinary-leftbinary>1) return {leftbinary+1,rightbinary-1};
return {-1,-1};
}
};
其中记录左右赋值的情况,rightbinary与leftbinary的初值不能是-1.