左闭右闭区间:(另一种为左闭右开区间)
注意middle的取值
class Solution { public int search(int[] nums, int target) { //首先关于(left + rigth)/2 取舍问题:int类型数据作除法会舍去小数部分 int left = 0; int right = nums.length - 1; //int middle = (left + rigth)/2; while (left <= right){ int middle = left + (right-left) / 2; if (nums[middle] > target){ right = middle - 1; } else if (nums[middle] < target){ left = middle + 1; } else { return middle; } } return -1; } }
第一次运行时出现超时问题,是因为把
int middle = left + (right-left) / 2;放在了循环体外面
然后
第二次出现问题(能运行但结果不对)是因为:忘记nums是一个数组,直接将middle的值当成数组值了,但是middle是数组下标,应改成nums[middle]标签:二分,right,target,nums,int,middle,查找,L2,left From: https://www.cnblogs.com/18191xq/p/17810003.html