有序的数据结构
right = numsize - 1
这种情况下,left = right是有意义的,故while(left <= right)
当nums[mid] > target时,right = mid - 1
当nums[mid] < target时,left = mid + 1
因为确定nums[mid]不是tartget
right = numsize
这种情况下,left = right没有意义,故while(left < right)
当nums[mid] > target时,right = mid
当nums[mid] < target时,left = mid + 1 注意此处还是mid+1,因为左边还是闭
因为是在左闭右开的区间中找,如果right = mid - 1,那就相当于把num[mid - 1]去掉了
最后附上C语言代码
// 左闭右闭
int search(int* nums, int numsSize, int target) {
int left = 0;
int right = numsSize - 1; // 此处为数组最大值的下标
int mid = 0;
while (left <= right)
{
mid = left + (right - left) / 2;
if (nums[mid] == target)
return mid;
else if (nums[mid] > target)
right = mid - 1;
else if (nums[mid] < target)
left = mid + 1;
}
return -1;
}
//左闭右开
int search(int* nums, int numsSize, int target) {
int left = 0;
int right = numsSize; // 此处为数组大小
int mid = 0;
while (left < right)
{
mid = left + (right - left) / 2;
if (nums[mid] == target)
return mid;
else if (nums[mid] > target)
right = mid;
else if (nums[mid] < target)
left = mid + 1; // 因为是左闭,还是mid + 1
}
return -1;
}