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]
.
如果不要求实现,用c++stl的lower_bound和upper_bound就可以了
class Solution { public: int lower_bound(vector<int>& nums,int numsSize,int target) { int low = 0,high = numsSize; while(low<high){ int mid = low+(high-low)/2; if(target <= nums[mid]){ high = mid; }else{ low = mid+1; } } return low; } int upper_bound(vector<int>& nums,int numsSize,int target) { int low = 0,high = numsSize; while(low<high){ int mid = low+(high-low)/2; if(target < nums[mid]){ high = mid; }else{ low = mid+1; } } return low; } vector<int> searchRange(vector<int>& nums, int target) { int numsSize = nums.size(); int low = lower_bound(nums,numsSize,target); vector<int> res; if(nums[low]!=target){ res.push_back(-1); res.push_back(-1); }else{ int high = upper_bound(nums,numsSize,target); res.push_back(low); res.push_back(high-1); } return res; } };
原文:http://www.cnblogs.com/zengzy/p/5002399.html