常规二分
class Solution { public int[] searchRange(int[] nums, int target) { if(nums == null || nums.length < 1){ return new int[]{-1,-1}; } int[] res = new int[]{-1,-1}; int len = nums.length; int left = 0; int right = len - 1; int mid = (left + right) >> 1;//寻找最小index时,不需要-1,因为右移会向下取整 while(left < right){//找leftIndex if(nums[mid] < target){ left = mid + 1; } else if(nums[mid] > target){ right = mid - 1; }else{ right = mid; } mid = (left + right) >> 1; } if(nums[left] == target){ res[0] = left; } right = len - 1; mid = ((left + right) >> 1) + 1;//因为要寻找最大的index,而右移会向下取整,所以需要+1,不进行+1,会出现死循环的情况 while(left < right){//找rightIndex if(nums[mid] < target){ left = mid + 1; } else if(nums[mid] > target){ right = mid - 1; }else{ left = mid; } mid = ((left + right) >> 1) + 1;//一定要+1,这是易错点 } if(nums[right] == target){ res[1] = right; } return res; } }
原文:https://www.cnblogs.com/yu-xia-zheng-ye/p/14068714.html