image.png

解决思路

二分查找

image.png

  1. //left表示是否为寻找左边坐标
  2. private int extremeInsertionIndex(int[] nums,int target,boolean left){
  3. int l = 0;
  4. int r = nums.length;
  5. //二分法
  6. while (l < r){
  7. int mid = (l + r) / 2;
  8. if (nums[mid] > target || (left && target == nums[mid]))
  9. r = mid;
  10. else
  11. l = mid + 1;
  12. }
  13. return l;
  14. }
  15. public int[] searchRange(int[] nums,int target){
  16. int[] targetRange = {-1,-1};
  17. //先寻找左边的坐标
  18. int leftIdx = extremeInsertionIndex(nums,target,true);
  19. if (leftIdx == nums.length || nums[leftIdx] != target)
  20. return targetRange;
  21. targetRange[0] = leftIdx;
  22. //再寻找有右边的坐标
  23. targetRange[1] = extremeInsertionIndex(nums,target,false)-1;
  24. return targetRange;
  25. }