Today brush leetcode time to do several channels and binary search (BS) related to the topic and found that there are two main problems: Some questions are not very intuitive to know with BS; BS with up bad corner case processing. Here I will summarize the usage and code templates BS.
1. When can algorithm BS?
There interval [start, end), and is defined in this section the mapping f and a condition A, assume that a part of [start, end) at the point x, such that the point x on the left for the map f satisfies the condition A, x point to the right of the map does not satisfy the condition a (here, in turn, have no problem, as the conditions are not satisfied a full x itself can be), if you know the conditions a and f, you can find a point x by half come.
Half is used to find the original partition in an ordered array, each point is a partition, it can be used to find. In the example [4, 3, 2, 1, 5, 6, 7, 8, 9], partition 5 is only one element.
2. BS algorithm templates
BS loop judgment condition Some people like to write left <= right, when we must consider is the final return of the return left or right, so I'm not used to write, think or use the left <right computer more in line with common sense, here left and right initial It refers to the corresponding [start, end) two endpoints.
1 def BS_template(): 2 left, right = start, end 3 while left < right: 4 # C++ 用 mid = left + ((right - left) >> 1), 否则可能加法溢出 5 mid = (left + right) >> 1 6 if f(mid) match A: 7 right = mid 8 else: 9 left = mid + 1 10 return left