1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution { public int[] searchRange(int[] nums, int target) { int[] ans=new int[2]; if(nums.length==0){ ans[0]=-1; ans[1]=-1; return ans; } ans[0]=binSearch(nums,target,0,nums.length-1); if(ans[0]>=nums.length||ans[0]<0||nums[ans[0]]!=target){ ans[0]=-1; ans[1]=-1; return ans; } else{ ans[1]=binSearch(nums,target+1,0,nums.length-1)-1; return ans; } }
int binSearch(int[] nums,int target,int begin,int end){ if(end<begin)return begin; else{ int mid=(begin+end)/2; if(nums[mid]==target&&(mid==0||nums[mid-1]!=target))return mid; else if(nums[mid]>=target)return binSearch(nums,target,begin,mid-1); else return binSearch(nums,target,mid+1,end); } } }
|