• 【LeetCode & 剑指offer刷题】分治法题3:Sqrt(x)


    【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

     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.

    C++
     
    /*
    本题其实与分治法无关
     
    方法:变形的二分查找法,找最后一个不大于目标值(x/mid)的数(由于返回整数,故可以用此方法)
    */
    class Solution
    {
    public:
        int mySqrt(int x)
        {
            if (x <= 1) return x;
            int left = 0, right = x;
            while (left < right)
            {
                int mid = left + (right - left) / 2;
                if (mid <= (x/mid) )
                    left = mid + 1;
                else
                    right = mid;
            }
            return right - 1; //通过返回right-1,改造返回第一个大于目标值(x/mid)的数 -> 返回最后一个不大于目标值的数
        }
    };
     
    /*
    方法二:牛顿迭代法
    对于求方程f(x) = 0的根,可用迭代式 xk+1 = xk - f(xk)/f'(xk)进行求解
    (特殊的简单迭代法xk+1 = p(xk),x = p(x)等价于f(x) = 0
     
    对此例x^2 = n,可推得xk+1 = (xk + n/xk)/2
    */
    class Solution
    {
    public:
        int mySqrt(int n)
        {
            if (n <= 1) return n;
            
            double x = 1, x_pre = 0;
            while (abs(x - x_pre) > 1e-6) //精度具体依题目要求
            {
                x_pre = x;
                x = (x + n / x) / 2;
            }
            return int(x);
        }
    };
     
     
  • 相关阅读:
    STP配置和选路规则
    Apache(基于端口号)
    Apache(基于主机名)
    Apache(基于IP地址)
    (Apache服务)个人用户主页功能
    c语言实现通讯录,包括增加名字,删除信息,查找,修改,排序
    C语言用函数指针的数组简单实现计算器功能
    指针与数组,指针与函数之间的关系
    循环
    SQLite不支持的SQL语法总结
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10229483.html
Copyright © 2020-2023  润新知