class Solution { public: void core_code(const vector<int>& nums, const int target, const int length, int start,int end,int& result_x,int& result_y) { if(start==end)//对于搜索到一个数,做如下判定 { if((start==0&&nums[start]==target)||(start!=0&&nums[start-1]<target&&nums[start]==target)) result_x=start; if((end==length&&nums[end]==target)||(end!=length&&nums[end+1]<target&&nums[start]==target)) result_y=end; return; } int len=end-start; int mid=(len)/2+start; if(nums[mid]<target) core_code(nums,target,length,mid+1,end,result_x,result_y); else if(nums[mid]>target) core_code(nums,target,length,start,mid,result_x,result_y); else { if(nums[mid+1]==target)//因为二分搜索,右侧开头一定mid+1,所以这里多一个判断 core_code(nums,target,length,mid+1,end,result_x,result_y); else result_y=mid; core_code(nums,target,length,start,mid,result_x,result_y); } } vector<int> searchRange(vector<int>& nums, int target) { vector<int> result(2,-1); int len=nums.size(); if(len==0)//惭愧,忘记判断边界了 return result; core_code(nums,target,len-1,0,len-1,result[0],result[1]); return result; } };
分析:好惭愧,这题做的我尴尬症犯了。