当前位置:网站首页>Leetcode (69) -- square root of X

Leetcode (69) -- square root of X

2022-07-01 14:14:00 SmileGuy17

Leetcode(69)——x The square root of

subject

Give you a nonnegative integer x , Calculate and return x Of Arithmetical square root .

Because the return type is an integer , Results are retained only Integral part , The decimal part will be Give up .

Be careful : No built-in exponential functions and operators are allowed , for example pow(x, 0.5) perhaps x ** 0.5 .

Example 1:

Input :x = 4
Output :2

Example 2:

Input :x = 8
Output :2
explain :8 The arithmetic square root of is 2.82842…, Because the return type is an integer , The decimal part will be removed .

Tips :

  • 0 0 0 <= x <= 2 31 − 1 2^{31 - 1} 2311

Answer key

Method 1 : Brute force

Ideas

​​   because x x x The value rounded down by the arithmetic square root of must be [ 0 , x ] [0, x] [0,x] in , So directly and violently from 0 0 0 Traversing x x x, Until you find the first square greater than x x x Value , It subtracts 1 1 1 Is the value we want to find .

Code implementation

My own :

class Solution {
    
public:
    int mySqrt(int x) {
    
        long n;
        for(n = 0; n*n <= x; n++);
        return n-1;
    }
};

Complexity analysis

Time complexity O ( x ) O(x) O(x), The worst case is from 0 0 0 Find the x x x Just found it
Spatial complexity O ( 1 ) O(1) O(1).

Method 2 : Two points search

Ideas

​​   because x x x The integer part of the square root ans \textit{ans} ans yes Satisfy k 2 ≤ x k^2 \leq x k2x Maximum k k k value , So we can do something about k k k Do a binary search , To get the answer .

​​   The lower bound of binary search is 0 0 0, The upper bound can be roughly set to x x x. In each step of binary search , We just need to compare the intermediate elements mid \textit{mid} mid The sum of the squares of x x x The size of the relationship , The range of the upper and lower bounds is adjusted by comparing the results . Because all our operations are integer operations , There will be no error , So when you get the final answer ans \textit{ans} ans after , There is no need to try again ans + 1 \textit{ans} + 1 ans+1 了 .

Code implementation

Leetcode Official explanation :

class Solution {
    
public:
    int mySqrt(int x) {
    
        int l = 0, r = x, ans = -1;
        while (l <= r) {
    
            int mid = l + (r - l) / 2;
            if ((long long)mid * mid <= x) {
    
                ans = mid;
                l = mid + 1;
            } else {
    
                r = mid - 1;
            }
        }
        return ans;
    }
};

my :

class Solution {
    
public:
    int mySqrt(int x) {
    
        long min = 0, max = x, mid;
        while(min <= max){
    
            mid = (min + max)/2;
            if(mid*mid < x){
    
                if((mid+1)*(mid+1) > x) break;
                else min = mid+1;
            }else if(mid*mid > x) max = mid-1;
            else break;
        }
        return mid;
    }
};

Complexity analysis

Time complexity O ( l o g x ) O(logx) O(logx), That is, the number of times needed for binary search .
Spatial complexity O ( 1 ) O(1) O(1).

Method 3 : Newton's iteration

Ideas

​​   Newton's iteration It is a method that can be used to quickly solve the zero point of a function .

For narrative purposes , We use it C C C Represents the integer for which the square root is to be found . obviously , C C C The square root of is a function
y = f ( x ) = x 2 − C y = f(x) = x^2 - C y=f(x)=x2C

Zero point of .

​​   The essence of Newton's iterative method With the help of Taylor series , Approaching zero point quickly from initial value . Let's take one x 0 x_0 x0 As an initial value , In each iteration , We find the point on the graph of the function ( x i , f ( x i ) ) (x_i, f(x_i)) (xi,f(xi)), Make a slope across the point as the derivative of the point f ′ ( x i ) f'(x_i) f(xi) The straight line of , The point of intersection with the horizontal axis is marked as x i + 1 x_{i+1} xi+1. x i + 1 x_{i+1} xi+1 Compare with x i x_i xi It's closer to zero . After many iterations , We can get a point of intersection very close to zero . The figure below shows the results from x 0 x_0 x0 Start iterating twice , obtain x 1 x_1 x1 and x 2 x_2 x2 The process of .

 Insert picture description here

Algorithm

We choose x 0 = C x_0 = C x0=C As an initial value .

In each iteration , We pass through the current intersection x i x_i xi, Find the point on the function image ( x i , x i 2 − C ) (x_i, x_i^2 - C) (xi,xi2C), Make a slope of f ′ ( x i ) = 2 x i f'(x_i) = 2x_i f(xi)=2xi The straight line of , The equation of a straight line is :
y l = 2 x i ( x − x i ) + x i 2 − C = 2 x i x − ( x i 2 + C ) \begin{aligned} y_l &= 2x_i(x - x_i) + x_i^2 - C \\ &= 2x_ix - (x_i^2 + C) \end{aligned} yl=2xi(xxi)+xi2C=2xix(xi2+C)

The intersection with the horizontal axis is the equation 2 x i x − ( x i 2 + C ) = 0 2x_ix - (x_i^2 + C) = 0 2xix(xi2+C)=0 Solution , This is the new iteration result x i + 1 x_{i+1} xi+1
x i + 1 = 1 2 ( x i + C x i ) x_{i+1} = \frac{1}{2}\left(x_i + \frac{C}{x_i}\right) xi+1=21(xi+xiC)

It's going on k k k After iterations , x k x_k xk And the real zero C \sqrt{C} C Close enough to , That's the answer .

details

  • Why choose x 0 = C x_0 = C x0=C As an initial value ?

​​   because y = x 2 − C y = x^2 - C y=x2C There are two zeros − C -\sqrt{C} C and C \sqrt{C} C. If we take a smaller initial value , It may iterate to − C -\sqrt{C} C This zero point , What we hope to find is C \sqrt{C} C This zero point . So choose x 0 = C x_0 = C x0=C As an initial value , Every iteration has x i + 1 < x i x_{i+1} < x_i xi+1<xi, zero C \sqrt{C} C On its left , So we must iterate to this zero .

  • When does the iteration end ?

​​   After each iteration , We will all be further away from zero , So when the intersection of two adjacent iterations is very close , We can conclude , The result at this time is enough for us to get the answer . Generally speaking , We can judge whether the difference between the results of two adjacent iterations is less than a minimal non negative number ϵ \epsilon ϵ, among ϵ \epsilon ϵ Generally, you can take 1 0 − 6 10^{-6} 106 or 1 0 − 7 10^{-7} 107.

  • How to get the final answer through the approximate zero obtained by iteration ?

​​   because y = f ( x ) y = f(x) y=f(x) stay [ C , + ∞ ] [\sqrt{C}, +\infty] [C,+] Is a convex function (convex function) And constant greater than or equal to zero , So as long as we choose the initial value x 0 x_0 x0 Greater than or equal to C \sqrt{C} C, The result of each iteration x i x_i xi Will always be greater than or equal to C \sqrt{C} C. So long as ϵ \epsilon ϵ The choice is small enough , Final result x k x_k xk It will only be slightly greater than the real zero C \sqrt{C} C. Given in the title 32 Bit integer range , The following will not happen :

The real zero is n − 1 / 2 ϵ n−1/2\epsilon n1/2ϵ, among n n n Is a positive integer , And the result of our iteration is n + 1 / 2 ϵ n+1/2\epsilon n+1/2ϵ. After reserving the integer part of the result, we get n n n, But the correct result is n − 1 n - 1 n1.

Code implementation

Leetcode Official explanation :

class Solution {
    
public:
    int mySqrt(int x) {
    
        long ans = x;
        while(ans * ans > x)
            ans = (ans + x/ans)/2;
        return ans;
    }
};

Complexity analysis

Time complexity O ( log ⁡ x ) O(\log x) O(logx), This method is quadratic convergent , Faster than binary search .
Spatial complexity O ( 1 ) O(1) O(1).

Method four : Pocket calculator algorithm

Ideas

​​  「 Pocket calculator algorithm 」 Is an exponential function exp ⁡ \exp exp Logarithmic function ln ⁡ \ln ln Instead of the square root function . We can use finite mathematical functions , Get the result we want to calculate .

We will x \sqrt{x} x Written as a power x 1 / 2 x^{1/2} x1/2, Then use the natural logarithm e e e Change the bottom , You can get
x = x 1 / 2 = ( e ln ⁡ x ) 1 / 2 = e 1 2 ln ⁡ x \sqrt{x} = x^{1/2} = (e ^ {\ln x})^{1/2} = e^{\frac{1}{2} \ln x} x=x1/2=(elnx)1/2=e21lnx

So we can get x \sqrt{x} x The value of the .

​​   Be careful : Because the computer cannot store the exact value of floating point numbers ( For the storage method of floating point numbers, please refer to IEEE 754, No more details here ), The parameters and return values of exponential function and logarithmic function are floating-point numbers , Therefore, there will be errors in the operation process . For example, when x = 2147395600x=2147395600 when , e 1 2 ln ⁡ x e^{\frac{1}{2} \ln x} e21lnx Calculation results and correct values 4634046340 Difference between 1 0 − 11 10^{-11} 1011, In this way, when taking the integer part of the result , You'll get 4633946339 The wrong result .

​​   So in the integer part of the result ans \textit{ans} ans after , We should find out ans \textit{ans} ans And ans + 1 \textit{ans} + 1 ans+1 Which one of them is the real answer .

Code implementation

Leetcode Official explanation :

class Solution {
    
public:
    int mySqrt(int x) {
    
        if (x == 0) {
    
            return 0;
        }
        int ans = exp(0.5 * log(x));
        return ((long long)(ans + 1) * (ans + 1) <= x ? ans + 1 : ans);
    }
};

Complexity analysis

Time complexity O ( 1 ) O(1) O(1), Because of the built-in exp Function and log Functions are generally fast , Here we regard its complexity as O ( 1 ) O(1) O(1).
Spatial complexity O ( 1 ) O(1) O(1).

原网站

版权声明
本文为[SmileGuy17]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207011404185404.html