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.

题目大意:

  给定非负整数x,求x的平方根

理  解 :

  方法一:暴力法,从i=1开始向后找,找到满足条件的i。应满足i*i<=x && (i+1)*(i+1)>x

      但这样有个弊端,即 i*i 会超过INT_MAX.所以应写为x/i>=i && x/(i+1)<(i+1)

      这个方法的效率很低,尤其当x很大时。

  方法二:用类似于二分法的方法找到满足条件的平方根mid。

      初始区间为[0,x]:mid为区间中间的值,

        当 x/mid < mid 时,右区间为mid

        当 x/mid = mid 时,mid即为x的平方根

        当 x/mid > mid 时,判断是否满足 x/(mid+1) < (mid+1) ,满足则mid为x的平方根;否则,左区间为mid

        更新mid为当前区间中间的值。效率明显很好。

代  码 C++ :

  方法一:

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;
    }
};

  方法二:

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;
    }
};

运行结果 :

  方法一:执行用时 : 240 ms  内存消耗 : 8.3 MB

  方法二:执行用时 : 0 ms  内存消耗 : 8.3 MB

猜你喜欢

转载自www.cnblogs.com/lpomeloz/p/10983097.html
今日推荐