letecode [69] - Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since 
             the decimal part is truncated, 2 is returned.

Subject to the effect:

  A square root of a given nonnegative integer x, x is seeking

Understanding:

  Method One: Violence Act, from i = 1 to start looking back, find satisfying the condition i. Should satisfy i * i <= x && (i + 1) * (i + 1)> x

      However, there is such drawbacks, i.e., i * i exceeds INT_MAX. It should be written as x / i> = i && x / (i + 1) <(i + 1)

      The efficiency of this method is very low, especially when a large x.

  Method two: find the square root mid satisfying the condition by a method similar dichotomy.

      The initial interval [0, x]: mid section of the intermediate values,

        When x / mid <mid, mid and right interval

        When x / mid = mid, mid is the square root of x

        When x / mid> mid, judges whether x / (mid + 1) <(mid + 1), x satisfies the square root of the mid; otherwise, the left mid interval

        Updated value of the current intermediate mid section. Efficiency is significantly good.

Code C ++:

  method one:

class Solution {
public:
    int mySqrt(int x) {
        if(x==0 || x==1) return x;
        
        for(int i=1;i<=x/2;++i){
            if(x/i>=i && x/(i+1)<(i+1))
                return i;
        }
        return x;
    }
};

  Method Two:

class Solution {
public:
    int mySqrt(int x) {
        if(x==0 || x==1) return x;
        int left=0,right=x,mid=x;
        while(left<=right){
            mid = (right-left)/2+left;
            if(x/mid<mid){
                right = mid;
            }else if(x/mid == mid){
                return mid;
            }else{
                if(x/(mid+1)<(mid+1))
                    return mid;
                left = mid;
            }
        }
        return x;
    }
};

operation result:

  Method a: when execution: 240  MS memory consumption:  8.3 MB

  Method two: execution:  0 MS   memory consumption:  8.3 MB

Guess you like

Origin www.cnblogs.com/lpomeloz/p/10983097.html