1. Find the target value in an orderly manner:
The problem of "finding the target value in a segmented array" can be transformed into the familiar "finding target value in an ordered array" problem by segmenting the array!
Source of ideas: Force button question: 1095. Find the target value in the mountain array .
According to the peak, the mountain array is divided into two sections, "ascending array" and "descending array", and binary search is performed respectively.
2. Mid-point mid update method:
int mid = (left + right) / 2;
This way of writing is fine in most cases.But in the scene where left and right are particularly large, left + right will overflow and get a negative number, The value of mid is then also negative. The improved wording is:
int mid = left + (right - left) / 2;
3, the boundary conditions update: prevent infinite loop
when left
and right
the difference is 1 or 0, if if else
appears the statement inside left = mid
, there will be an endless loop. Because mid
always equals left
.
if (check(mid)) {
// 下一轮搜索区间是 [mid + 1, right]
left = mid;
} else {
right = mid-1;
}
Should be modified to round up:
int mid = left + (right - left + 1) / 2;
if (check(mid)) {
left = mid;
} else {
right = mid - 1;
}
Reference: Detailed introduction of dichotomy
to sum up:
1, binary search algorithm time complexity of O (LGN);
2, if if else
occurs inside the statement left = mid
, mid modified to be rounded up int mid = left + (right - left + 1) / 2;
.