【Two points summary template】

During the few months of internship, it has nothing to do with java, and I have to forget the questions I wrote. I will review it during the isolation period and look back at Da Xuecai's two points again.

Summarize it yourself, so that you can review it later

Here, the dichotomy is divided into two templates, find a condition for yourself, let the number present a dichotomy, and then find mid, if mid is at the point of the condition you are looking for

1、

        If mid is in the green part, that is, the condition point we are looking for is on the left side of mid, and mid may also be this condition point, then we will continue to filter to the left, and the filter range will change from [L, R] to 【L, M】;

        If mid is in the red color part, that is, the condition point we are looking for is on the right side of mid, we continue to filter to the right, and the screening range will change from [L, R] to [mid+1, R]

2、

        If mid is in the red part, that is, the condition point we are looking for is on the right side of mid, and mid may also be this condition point, then we will continue to filter to the right, and the filter range changes from [L, R] to [mid , R]

        If mid is in the green part, that is, the condition point we are looking for is on the left side of mid, we continue to filter to the left, and the screening range will change from [L, R] to [L, mid-1]

Therefore, you can also directly judge the number of templates based on a condition you wrote to improve the following code.

Here we take [ 367. Effective perfect square numbers ] as an example to go through the dichotomy process.

1. First divide the boundary into two parts. int left = 0, right = num;

2、while(left < right){

                long mid = left + right >> 1;

                if() 

        }        

 3. The condition of the check function designed here is: mid * mid > num. Note that mid * mid is used here, and the int type is limited, so the long type is used.

4. Then think about it. If mid * mid < num, it means that the condition point is still on the right side of mid, and mid may also be. If you continue to filter to the right, it will change to L and not change to R, that is, [L, R] --- >【mid, R】; if mid * mid > num, it means that the condition point is on the left side of mid, filter to the left, then L will not change, change to R, that is, 【L, R】 ---> 【L, mid-1】

5. Supplementary code

        while(left < right){

                        long mid = left + right >> 1;

                        if(mid * mid < num)  left = mid;

                        else if (mid * mid > num) right = mid -1;

                } 

              

So left + right +1 >> 2;

The completion code is:

Both template 1 and template 2 can be written. 

 

 

Guess you like

Origin blog.csdn.net/Sean_Asu/article/details/125262278