提交錯誤:陣列訪問越界
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 }