The binary lookup algorithm is simple, but it is also common in interviews, often used to find a particular location in an orderly sequence. The main topics used for this algorithm in Leetcode are:
Search Insert Position
Search for a Range
SQRT (x)
Search a 2D Matrix
Search in rotated Sorted Array
Search in rotated Sorted Array II
This kind of topic can be divided into the following four kinds of questions basically:
1. Search Insert position and search for a range are the basic usage of binary lookup. The basic idea is to take the middle each time, if equal to the goal is to return, otherwise, according to the size of the relationship cut half, so the time complexity is O (LOGN), Space complexity O (1). Take search Insert position as an example, the key code is as follows:
int l = 0;
int r = a.length-1;
while (l<=r)
{
int mid = (l+r)/2;
if (A[mid]==target) return
mid;
if (a[mid]<target)
L = mid+1;
else
r = mid-1;
}
return l;
So when the loop stops, if it's not exactly found that the target,l point to the element that is exactly the same as the target, the L and R may be out of bounds, but if the bounds are greater than (less than) target and the maximum (min). The Search for a range is a better way to explain this problem. The idea is to use a binary lookup to find one of the target, and then to the left and right to locate the target edge. We mainly look for the edge (looking back) code:
int newl = m;
int newr = a.length-1;
while (NEWL<=NEWR)
{
int newm= (NEWL+NEWR)/2;
if (a[newm]==target)
{
newl = newm+1;
}
else
{
newr = newM-1;
}
}
RES[1]=NEWR;
Our goal is to find the right edge of target at the back, because the left side is already equal to target, so the judgment condition is equal to the right, greater than the left to look, according to the above, when the loop stops, L point to the element should be exactly greater than the target,r point should be equal to target So the R at this point is exactly what we want. It's the same with looking forward to the edge.
2. SQRT (x) is the problem of numerical processing, but it can also be solved by the idea of binary search. Because we know the scope of the result, we take the left and right boundaries, and then we cut off half of the conditions, until the left and right are met. The time complexity of the algorithm is O (LOGX), and the space complexity is O (1). This is also the basic use of binary lookup. The code is as follows:
public int sqrt (int x) {
if (x<0) return-1;
if (x==0) return 0;
int l=1;
int r=x/2+1;
while (l<=r)
{
int m = (l+r)/2;
if (m<=x/m && x/(m+1) <m+1) return
m;
if (x/m<m)
{
r = m-1;
}
else
{
L = m+1;
}
}
return 0;
}
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/