Binary template
- Algorithm idea: Suppose a target value in a closed interval
[l, r]
, each time interval length is reduced by half, when[l, r]
the time, i.e., to find the target.
A template
The interval into [l, mid]
and [mid + 1, r]
when it is updating operation l = mid + 1
or r = mid
, without calculation 1 mid.
while (l < r) {
int mid = l + r >> 1;
if (check(mid)) r = mid;
else l = mid + 1;
return l;
}
Template two
The interval into [l, mid - 1]
and [mid, r]
when it is update r = mid - 1
or l = mid
add 1 when calculating mid.
while (l < r) {
int mid = l + r + 1>> 1;
if (check(mid)) l = mid;
else r = mid - 1;
return l;
}