p38 实现平方根函数 (leetcode 69)

一:解题思路

第一种方法:利用二分搜索的思想来做。

第二种方法:利用牛顿迭代法来做。两种方法的时间复杂度都为O(log(n)),空间复杂度为:O(1)

二:完整代码示例 (C++版和Java版)

二分搜索C++:

class Solution 
{
public:
    int mySqrt(int x) 
    {
        int low = 0;
        int high = x;

        while (low <= high)
        {
            long mid = low + (high - low) / 2;
            long mid2 = mid * mid;

            if (mid2 > x)
            {
                high = mid - 1;
            }
            else if (mid2 < x)
            {
                low = low + 1;
            }
            else
            {
                return mid;
            }
        }

        return (int)high;
    }
};

二分搜索Java:

class Solution
{
    public int mySqrt(int x)
    {
          long low=0;
          long high=x;

          while(low<=high)
          {
              long mid=low+(high-low)/2;
              long mid2=mid*mid;
              
              if(mid2>x)
              {
                  high=mid-1;
              }
              else if(mid2<x)
              {
                  low=mid+1;
              }
              else
              {
                  return (int)mid;
              }
          }

          return (int)high;
    }
}

牛顿法C++:

class Solution 
{
public:
    int mySqrt(int x) 
    {
        long num = x;

        while (num*num > x)
        {
            num = (num + x / num) / 2;
        }

        return (int)num;
    }
};

牛顿法Java:

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

猜你喜欢

转载自www.cnblogs.com/repinkply/p/12498711.html
今日推荐