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]
.
思路1:二分查找找到等于target的位置,再寻找target的左右边界,注意别越界!
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int temp[] = { -1, -1 }; vector<int> ret(temp, temp + 2); if (nums.size() == 0) return ret; int l = 0; int r = nums.size(); int mid = 0; while (l <= r){ mid = (l + r) / 2; if (nums[mid] == target) break; else if (nums[mid]>target) r = mid - 1; else l = mid + 1; } if (nums[mid] != target){ return ret; } l = r = mid; while (nums[l] == target&&l>0) l--; while (r<nums.size() && nums[r] == target) r++; if (nums[l] != target) l++; if (r>=nums.size()||nums[r] != target)//注意r可能为nums.size(),这种情况也要r-- r--; ret[0] = l; ret[1] = r; return ret; } };
思路2:类似于lower_bound和upper_bound的实现
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int a[]={findLow(nums,target),findHigh(nums,target)}; vector<int> ret(a,a+2); return ret; } int findLow(vector<int>& nums,int target){ int l=0,r=nums.size()-1; while(l<=r){ int m=(l+r)>>1; if(nums[m]<target) l=m+1; else r=m-1; } if(nums[l]==target) return l; return -1; } int findHigh(vector<int>& nums,int target){ int l=0,r=nums.size()-1; while(l<=r){ int m=(l+r)>>1; if(nums[m]>target) r=m-1; else l=m+1; } if(nums[r]==target) return r; return -1; } };