69. Sqrt(x)

来源:互联网 发布:"笨办法"学python 编辑:程序博客网 时间:2024/06/10 03:15

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

Example 1:

Input: 4Output: 2

Example 2:

Input: 8Output: 2Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.

这道题如果用暴力枚举法做会超时,所以要用时间复杂度更低的方法。
最容易的是二分法,每次都可以把查询范围缩小一半。注意这里为了防止溢出可以用long long:

class Solution {public:    int mySqrt(int x) {        long long i = 0, j = (x / 2) + 1;        long long mid = (i + j) / 2;         while (i <= j) {            long long sqrt = mid * mid;            if (sqrt == x) return mid;            else if (sqrt < x) i = mid + 1;            else j = mid - 1;            mid = (i + j) / 2;        }        //这里肯定要return i和j里相对较小的那个,所以是j        return j;    }};

还有一个算法就是数值方法课讲过的牛顿迭代法。牛顿迭代法的思想和迭代公式可以参考百度百科。
这道题其实相当于给出n,求f(x)=x2n的零点。可以使用牛顿迭代公式,求出xi+1xi的关系式:
xi+1=xix2in2xi=12(xi+nxi)
可以根据递推式写出代码,注意这里先用double计算,最后再转成int:

class Solution {public:    int mySqrt(int x) {        if (x == 0) return 0;        double last = 0;        double pre = 1;        while (pre != last) {            last = pre;            pre = (last + x / last) / 2;        }        return (int)pre;    }};
原创粉丝点击