题目
Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
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]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
根据target在数组中查找所在范围的下标,在找到target时便判断beg和end的大小,并随时改变。
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int beg=nums.size(),end=-1;
bool find=false;
for(int i=0;i<nums.size();++i){//顺序检索数组,找到target时就改变beg和end的值,beg始终是所有target下标中最小的,end始终是最大的
if(nums[i]==target){
beg=min(beg,i);
end=max(end,i);
find=true;
}
}
if(!find){//处理未找到target的情况
return {-1,-1};
}
return {beg,end};
}
};