【LeetCode】No.69. Sqrt(x) -- Java Version

109 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第5天,点击查看活动详情.

题目链接:leetcode.com/problems/sq…

1. 题目介绍(Sqrt(x))

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

【Translate】: 给定一个非负整数x,返回x的平方根向下舍入到最接近的整数。返回的整数也应该是非负的。

You must not use any built-in exponent function or operator.

【Translate】: 不能使用任何内置指数函数或运算符。

For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.

【Translate】: 例如,你不能在C中使用pow(x,0.5),或者在Python中使用 x ** 0.5。

【测试用例】:

testcase1

【条件约束】:

Constrants

2. 题解

2.1 Newton Method

牛顿迭代法(Newton's method)又称为牛顿-拉夫逊(拉弗森)方法(Newton-Raphson method),它是牛顿在17世纪提出的一种在实数域和复数域上近似求解方程的方法。 newton method

function newton sqrt 根据公式,我们就可以直接代入求解平方根了,题解代码如下:

// PS:有个小疑惑就是这里其实使用了操作符,只是没直接对x进行操作。
// 原题解来自于StefanPochmann的3-4 short lines, Integer Newton, Every Language

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

act1

2.2 binary search

原题解来自于seekers01的Simple Java Solution with comments - 1ms - O(log n)。使用二分法来完成平方根还是比较容易被想到的,在有限的“区间”中,每次通过筛选一半的元素,到最终只剩下一个数(收敛),这个数就是题目要求的取整的平方根整数。

// using binary search
class Solution {
    public int mySqrt(int x) {
        if(x <= 1) return x;
        int start = 1;
        int end = x/2;
        
        while(start < end) {
            // start is not always moving and hence we can get stuck in infinite loop with mid calculation
            // Adding 1 to mid everytime to ensure we always move the mid
            int mid = (start + (end-start)/2) + 1;
            
            // use division instead of multiplication to avoid overflow
            int div = x/mid;
            if(div == mid) return mid;
            if(div > mid) start = mid;
            else end = mid-1;
        }
        
        return start;
    }
}

act2

3. 参考资料

[1] 牛顿迭代法 | 百度百科

[2] 牛顿迭代法原理讲解 | CSDN

[3] 牛顿迭代法几何定义理解 | 知乎

[4] 如何用牛顿法求一个数的平方根 | 程序猿

[5] 如何用二分法算出平方根? | CSDN