针对一组单调(增、减)的数列
12 15 23 27 34 39 41 49 52 56
查找目标key:39 在哪个位置,就可以用二分查找
(1)写while循环时,left < right 还是 left <= right
(2)if (number [middle] > target),更新右区间,那么right = middle 还是right = middle-1
?区间的定义可以理解为循环的不变量,在边界处理的时候要坚持区间开闭的原则
一般两种情况:[left,right]? 左闭右闭??[left,right) 左闭右开
left=0;
right?= num.size-1;
while ( left <= right ){
? ? middle = (left+right)/2;
? ? if( num [middle] > targrt )
? ? ? ? ? ? right = middle -1;
? ? else if (num[middle]? < target )
? ? ? ? ? ? left = middle+1;
? ? else return middle;
}
return? -1;
left = 0;
right?= num.size;
while ( left <?right ){
? ? middle = (left+right)/2;
? ? if( num [middle] > targrt )
? ? ? ? ? ? right = middle;
? ? else if (num[middle]? < target )
? ? ? ? ? ? left = middle+1;
? ? else return middle;
}
return? -1;