题目
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的起始和终止位置。
算法的运行复杂度至少要是O(log n)。
如果在数组中找不到目标,返回[-1,-1]
。
例如,
给定[5,7,7,8,8,10]
和目标值8,
返回[3,4]
。
分析
这道题还是比较容易解的,数组是已排序的,算法要求是O(log n),用二分查找即可。
我的做法是用二分查找找到 target 的index,然后沿着这个index的前后,找到target的范围
代码
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> result = {-1,-1};
int start=0,end= nums.size()-1,mid;
while(start<=end){
mid = (end+start)/2;
if(target>nums[mid])
start = mid+1;
else if(target<nums[mid])
end = mid-1;
else{
int temp = mid;
while(temp>=0 && nums[temp] == target)
temp --;
result[0] = temp+1;
temp = mid;
while(temp<nums.size() && nums[temp] == target)
temp++;
result[1] = temp-1;
break;
}
}
return result;
}
87 / 87 test cases passed.
Runtime: 9 ms