1.题目
Given a sorted array of integers, 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]
.
2.思路
二分查找,然后向两边延伸。。。
class Solution {
public:
int bSearch(vector<int> &nums,int target){
int left = 0,right = nums.size()-1,mid = 0;
while(left <= right){
mid = (right - left)/2 + left;
if(nums[mid] == target)
return mid;
else if(nums[mid] > target)
right = mid - 1;
else
left = mid + 1;
}
return -1;
}
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ans(2,-1);
int index = bSearch(nums,target);
if(index == -1) return ans;
else{
int left = index,right = index;
while(left >=0 && nums[left] == target)
left--;
while(right < nums.size() && nums[right] == target)
right++;
ans[0] = left+1;
ans[1] = right-1;
return ans;
}
}
};