34 Search for a Range(目标数的范围Medium)

时间:2022-03-22 16:21:11

题目意思:递增数组,找到目标数的范围,找不到则返回[-1,-1]

思路:折半查找

 class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int start=,end=nums.size()-;
vector<int> ans;
while(start<=end){
int temp=(start+end)/;
if(nums[temp]>target){
end=temp-;
}
else if(nums[temp]<target){
start=temp+;
}
else if(nums[temp]==target){
int flag1=temp,flag2=temp;
while(flag1>&&nums[flag1-]==target){
--flag1;
}
while(flag2<nums.size()-&&nums[flag2+]==target){
++flag2;
}
ans.push_back(flag1);
ans.push_back(flag2);
return ans;
}
}
ans.push_back(-);
ans.push_back(-);
return ans;
}
};

时间复杂度:O(logn)

运行时间:12ms

代码太冗余了,以后再精简吧