基本思想:
有序递增重复序列边界二分查找,详见二分总结博客;
详细代码:
int left_bound(vector&nums,int target){ int l=0; int r=nums.size()-1; while(l<=r){ int mid=l+(r-l)/2; if(nums[mid]==target){ r=mid-1; }else if(nums[mid]>target){ r=mid-1; }else{ l=mid+1; } } if(l==nums.size()||nums[l]!=target) return -1; return l;}int right_bound(vector&nums,int target){ int l=0; int r=nums.size()-1; while(l<=r){ int mid=l+(r-l)/2; if(nums[mid]==target){ l=mid+1; }else if(nums[mid]>target){ r=mid-1; }else{ l=mid+1; } } if(r==-1||nums[r]!=target) return -1; return r;}vector searchRange(vector& nums, int target) { if(nums.size()<1) return vector{-1,-1}; if(nums.size()==1) if(target==nums[0]) return vector{0,0}; else return vector{-1,-1}; int l= left_bound(nums,target); int r= right_bound(nums,target); return vector{l,r};}