34. Search for a Range
就是二分搜索,做三遍。
1.第一遍找到第一个target
2.第二遍找到左侧的边界
3.第三遍找到右侧的边界
1 public int[] searchRange(int[] nums, int target) { 2 int[] res = new int[2]; 3 res[0] = -1; 4 res[1] = -1; 5 if(nums == null || nums.length == 0) { 6 return res; 7 } 8 int low = 0; 9 int high = nums.length - 1; 10 int mid = 0; 11 boolean found = false; 12 while(low <= high) { 13 mid = low + (high - low) / 2; 14 if(nums[mid] == target) { 15 found = true; 16 break; 17 } else if(nums[mid] > target) { 18 high = mid - 1; 19 } else { 20 low = mid + 1; 21 } 22 } 23 if(found == true) { 24 int l = mid; 25 int r = nums.length - 1; 26 int m = 0; 27 while(l <= r) { 28 m = l + (r - l) / 2; 29 if(nums[m] == target) { 30 l = m + 1; 31 } else { 32 r = m - 1; 33 } 34 } 35 res[1] = r; 36 l = 0; 37 r = m; 38 while(l <= r) { 39 m = l + (r - l) / 2; 40 if(nums[m] == target) { 41 r = m - 1; 42 } else { 43 l = m + 1; 44 } 45 } 46 res[0] = l; 47 } 48 return res; 49 }