34. Find First and Last Position of Element in Sorted Array
对mid两边进行binary search 得出边界
1 class Solution { 2 public int[] searchRange(int[] nums, int target) { 3 int[] res = {-1, -1}; 4 if(nums.length == 0) return res; 5 int[] bi = biSearch(nums, target, 0, nums.length - 1); 6 if(bi[0] == Integer.MAX_VALUE) { 7 return res; 8 }else { 9 return bi; 10 } 11 12 } 13 14 public int[] biSearch(int[] nums, int target, int lo, int hi) { 15 int[] res = {Integer.MAX_VALUE, Integer.MIN_VALUE}; 16 17 while(lo <= hi) { 18 int mid = lo + (hi - lo)/2; 19 if(nums[mid] == target) { 20 res[0] = Math.min(mid, biSearch(nums, target, lo, mid-1)[0]); 21 res[1] = Math.max(mid, biSearch(nums, target, mid+1, hi)[1]); 22 return res; //因为是recursive的 所以在这边就可以返回 23 }else if(nums[mid] < target) { 24 lo = mid + 1; 25 }else { 26 hi = mid - 1; 27 } 28 } 29 return res; 30 } 31 }