提交错误:数组访问越界
1.验证数组越界的语句要放在执行语句的前面,要不然前面报错无法进行到后面部分
2.本题使用两次二分查找,左边界找到后,将rigiht指针设置成mid-1,继续查找更左的边界,右边界同理将left设置成mid+1
3.new int[ ]{1,1} 新数组创建方式
1 class Solution { 2 public int[] searchRange(int[] nums, int target) { 3 int leftBorder=-1,rightBorder=-1,left=0,right=nums.length-1; 4 while(left<=right){ 5 int mid=(left+right)/2; 6 if(nums[mid]<target){ 7 left=mid+1; 8 } 9 else if(nums[mid]>target){ 10 right=mid-1; 11 } 12 else{ 13 leftBorder=mid; 14 right=mid-1; 15 } 16 } 17 left=0; 18 right=nums.length-1; 19 while(left<=right){ 20 int mid=(left+right)/2; 21 if(nums[mid]<target){ 22 left=mid+1; 23 } 24 else if(nums[mid]>target){ 25 right=mid-1; 26 } 27 else{ 28 rightBorder=mid; 29 left=mid+1; 30 } 31 } 32 return new int[]{leftBorder,rightBorder}; 33 } 34 }
标签:Q3,right,int,mid,rightBorder,数组,LeetCode34,排序,left From: https://www.cnblogs.com/cff1/p/18226371