Leetcode Summary--two points to find a chapter

Source: Internet
Author: User
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;
}
Note here that the conditions for equality are not simple m = = x/m, but m<=x/m && x/(m+1) <m+1, because the output is integral, sqrt (14) =3 but 3!= 14/3. So we need a range box to live the result. In addition, according to the characteristics of the binary lookup algorithm, if you can't just m==x/m stop, then the number that r points to is exactly the value of the result rounding. So we can also write this:
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) return
            m;
        if (x/m<m)
        {
            r = m-1;
        }
        else
        {
            L = m+1;
        }
    }
    return r;
}
3. Search a 2D matrix is a multi-dimensional application of the binary search algorithm, through observation is not difficult to find, the input matrix is orderly and orderly between the rows, so find only need to search by row first, locate in which row after the column lookup can be, two-point search, time complexity is O (logm+logn ), with only two auxiliary variables in space, and therefore O (1), no longer repeat here.

4. Search in rotated Sorted array and search in rotated Sorted Array II is a variant of the binary lookup algorithm. In the Search in rotated Sorted array, at first glance, the sensory array is not ordered, you can not use the binary search algorithm, but the careful analysis will find that, because only rotate once, if two points, the total half is orderly, and the other half does not overlap, All we need to do is check the ordered half of the two elements to determine which half of the target may be. Specifically, suppose the array is a, the left edge is L, the right edge is R, and the middle position is M. In each iteration, it is divided into three different situations:
(1) If target==a[m], then M is the result we want, direct return;
(2) if A[M]&LT;A[R], then the description from M to R must be orderly (not affected by the rotate), then we just need to determine whether the target is between M to R, if it is to move the left edge to the m+1, or target in the other half, That is, move the right edge to the m-1.
(3) If A[M]&GT;=A[R], then the description from L to M must be orderly, just to determine whether the target is within this range, the corresponding move edge can be.
According to the above method, each time we can cut off half of the data, so the algorithm time complexity is O (LOGN), Space complexity is O (1). Search in rotated Sorted Array II has duplicate elements, according to just thought, after two points although half is orderly, but we will encounter the middle and edge of the same situation, we lost the information on which side of the order, because which side may be ordered results. Assuming the original array is {1,2,3,3,3,3,3}, then the rotation may be {3,3,3,3,3,1,2}, or {3,1,2,3,3,3,3}, so that we judge the left edge and center of the time is 3, if we are looking for 1 or 2, We don't know which half we should jump to. The solution can only be to move one step toward the edge, until the edge and middle are not equal or meet, which leads to the possibility of not cutting off half. So the worst-case scenario (for example, all is an element, or only one element is different from other elements, and he is at the last) will appear each move one step, the total is n step, the algorithm time complexity becomes O (n).

In general, the binary search algorithm is not difficult to understand, but in the actual interview process may appear various variants, how flexible use is the key to success. We have to grasp the "orderly" characteristics, once found that the input has "orderly" characteristics, we can consider whether the use of binary lookup algorithm to solve the problem.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.