two points answer

two points answer

1. Usage scenarios

The binary answer is generally used to solve the minimum or maximum value that meets the conditions. When we encounter these two problems, we can generally use the binary answer to solve the problem.

2. What is a binary answer

The binary answer is a method of halving all possible answer intervals, continuously reducing the range, and finally determining the answer.

3. Find the minimum value

//求最小值
int getAnswer(int l, int r) {
    int mid;
    while(l < r) {
        mid = (r + l) / 2;
        if(check(mid)) {
            r = mid;
        }
        else {
            l = mid + 1;
        }
    }
}

We can know that if the minimum value is required, then the value that satisfies the condition is assigned to the right boundary, and the unsatisfied value plus one is assigned to the left boundary. When l is equal to r or l>r, it means that the matching minimum value has been queried.

4. Find the maximum value

int getAnswer(int l, int r) {
    int mid;
    while (l<r) {
        mid = (r + l + 1) / 2;
        if (check(mid)) {
            l = mid;
        }
        else {
            r = mid - 1;
        }
    }
}

Similarly, if the maximum value is required, then the smaller value that meets the conditions needs to be discarded, that is, the left boundary is assigned the qualified point, and the right boundary is assigned the unqualified value minus one. Continue to query, and finally the maximum value that meets the conditions is left. Where mid = (r + l + 1) / 2 is to prevent infinite loops, because when l=r+1 just meets the condition, r+l/2=l, it will loop infinitely.

5. The idea of ​​the check function

Since we have chosen to use the dichotomous method to solve the problem, when we check, we should confirm the answer when we know the answer, that is, not to imagine from the general thinking direction, but to verify. The check function is often based on the assumption that the answer is known to verify that it is correct.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324647321&siteId=291194637