Do you really understand the two-point notation? two

Source: Internet
Author: User

To tell the truth, I did not fully understand the two-point lookup of the various formulations, resulting in the writing of a variety of two-point boundary when I always do not clear the boundary value, so I can only through the violent enumeration of these boundary values, to a test, this is really low efficiency. Therefore, the painful lesson, must be two points of the wording thoroughly understand, there is this article. the type of the two-part notation

There are many types of dichotomy, the most common is the two-point search for the most common wording. The code is as follows:

BOOL Bfind (int a[], int left, int. right, int tag)
{for
    (; left <= right;) {
        int mid = (left + right) >> 1;
        if (a[mid] = = tag)
            return true;
        else
            A[mid] < tag? l = mid + 1:r = mid-1;
    }
    return false;
}

As I said earlier, this is only the most common two points, in fact, the two can also achieve non-equivalent search, such as the two points in peacetime to seek the upper bound, two points for the Nether and so on.

I'll use the multiplication principle to tell you how many of the two-point lookups are written. The opening and closing of the interval-[open interval or closed interval] around the end point-[this endpoint is and the above interval closed and close, the specific performance is Zokai or left, the right open or the right closed] midpoint is rounded or into one-[in the calculation of the midpoint of the time is (left + right) >> 1 or (left + Right + 1) >> 1] greater than or less than-[this corresponds to the upper and lower bounds of the problem] takes equal to-[is greater than or equal to or less than] the first or last-[find the first position greater than the target or find the last position greater than the target]

Each option is two possibilities, so there is a total of 26=64 2 6 = 64 2^6=64 notation. That is, choosing one of these six options can make up a two-point problem.

So many kinds of two points, is not every kind of two to remember it. Sure don't, or I will write this blog why. Next I'll tell you a common method.

First look at a topic, there is a point. Topic Background

Counts the number of occurrences of a number in a sorted array. Problem Analysis

Practice See Sword refers to the Offer66 question of the day 6-the seventh day of the first question. Code

Class Solution {public
:
    int GETNUMBEROFK (vector<int> data, Int. k) {
        int pre, Last, L, R;
    Nether
        for (l = 0, r = data.size (); l < R;) {
            int mid = (L + r)/2;
            if (Data[mid] >= k)
                r = Mid;
            else
                L = mid + 1;
        }
        Pre = R;

    Upper bound
        for (L =-1, r = (int) data.size ()-1; l < R;) {
            int mid = (L + R + 1)/2;
            if (Data[mid] <= k)
                L = mid;
            else
                r = mid-1;
        }
        last = l;
        return last-pre + 1;
    }
};
detailed

In this topic, we want to use a two-point to find the Nether, a two-point to the upper bounds. seeking the Nether

What is the definition of the nether, is to find a number, the number is the number of the first greater than or equal to K, the position of this number is the lower bound;

Notice the boundary of the two points I set to L = 0, r = data.size (), this is a left closed right open interval, at the midpoint I use MID = (L + r)/2, after the end of the two, L equals R;

The nether is positioned close to the left end, so we start looking from the left endpoint, so we can see that the position of the L in the two points is closer to the right end of the step (and therefore to one), and R is just the function of narrowing the scope;

The right endpoint is a starting point, which is to handle the case that there is not a number in the ordered array than K, so if the lookup fails, L and R can point to an empty position, that is, the last position of the array, the idea of the "left closed right open" interval in the program is the same;

As for why the midpoint should be rounded down, the reason is this: if you want to find this ordered array in order to find the nether, you will find out where to start. Must be the first element on the left to find Ah, you can not start from the second element to find it, this is why to take down the whole reason, the downward rounding to avoid missing the best solution;

If you do not understand, then I give an example you know, the array is [-2], k = 3,l = 0, R = 1, and then you two points upward into one, then Mid = (0 + 1 + 1)/2 = 1, then you will find that mid is not in the array, how can ah, mid is the midpoint of the interval , it is bound to be in the array ah. This is why the middle of the lower bound to be rounded down;

There is also a point to always remember, after the end of the two, L = R, so finally L, R are the answer. ask for upper bounds

Just said to seek the nether, the upper bound also do the same.

To find the upper bound is the last number greater than or equal to K position, we put the array in turn, with the right end as the starting point to search, this time the first element less than or equal to K is the upper bound of the original problem;

You turn the upper bounds into a lower bound, it is not everything in the code is taken for granted;

R = Data.size ()-1, L =-1, because the array in turn, so the right end is the starting point, the end of the position is the first element in front of a position;

Mid = (L + R + 1)/2, because the array is reversed, so the upward one here is actually the downward rounding after the reverse. Summary

You can see that the upper bound can be converted to the lower bound to do, so here is a detailed summary of the practice of seeking the nether.

The first thing in the nether is to determine the range of the left and right end points, because the lower bound is the first to meet the condition conditions , where the condition is to take this method of the nether to generalize, the first to meet the conditions of the position, therefore, the left endpoint as the starting point;

The latter position of the last element is used as the end point, in order to obtain a reasonable value in the solution without satisfying the condition (the latter position of the last element indicates that the nether is not found);

The midpoint is taken close to the beginning of the end, depending on the location of the next selection of downward rounding or upward into one;

In the narrow range, if the mid satisfies the condition, then the R = Mid, this can narrow the range ([mid + 1, R) is certainly not satisfied with the condition, but mid may be the answer, it's OK, we let l to equal to mid-line, R just narrow the range), and, this can guarantee there must be a solution;

If the mid does not meet the conditions, it makes L = mid + 1, because [L, mid] is bound to not meet the conditions, so let L step closer to R to find the answer to meet the conditions.

In this way, you can follow this method of finding the nether in either of the 64 binary points. Templates

Class Solution {public:static bool Cmp1 (const int &AMP;A, const int &b) {return a >= B;
    } static bool Cmp2 (const int &AMP;A, const int &b) {return a <= B;
        }//Seek the Nether int Getdown (vector<int> data, int k, BOOL (*CMP) (const int &, const int &)) {
        int L, R; for (l = 0, r = data.size (); l < R;)
            {int mid = (L + r)/2;
            if (!cmp (Data[mid], k)) L = mid + 1;
        else R = Mid;
    } return L; }//seek upper bound int getup (vector<int> data, int k, BOOL (*CMP) (const int &, const int &)) {in
        T L, R; for (L =-1, R = Data.size ()-1; l < R;)
            {int mid = (L + R + 1)/2;
            if (!cmp (Data[mid], k)) R = mid-1;
        else L = mid;
    } return L; } int GETNUMBEROFK (vector<int> data, int k) {int up= GetUp (data, K, cmp2), down = Getdown (data, K, CMP1);
        return Up-down + 1;
return GetUp (data, K, &cmp)-Getdown (data, K, &cmp) + 1; };

This template is written in the context of the above topic, with a function pointer, so that the problem can be generalized, this function pointer to a comparison function, this comparison function you write the legal conditions, STL S T L STL is so designed their lower_bound. other

Since the STL S T L STL, I'll tell you again upper_bound function, Lower_bound function and we said above to seek the nether is exactly the same, but, Upper_bound is a bit different, it is also the upper bound, but the answer is the upper bound of the latter position;

Using what we have just said for the nether, we can adapt the method to find the nether, so that it can also ask for the upper bound, so that the modified function is the same as upper_bound, but such an adapted function is only suitable for the above topic background, specific problems specific analysis, which is why the STL S T L STL has lower_bound Why do you want to engage in a upper_bound reason;

The function body of the nether is not moved, just change the CMP2. Think about the position of the last element greater than or equal to K, and if we get the position of the first element greater than K, then this position is the next position of the answer, so the contents of CMP2 are changed to return a > b; and then call Getdown (data, K, CMP2) The next position of the upper bound can be obtained.

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.