[LeetCode] 69. 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.

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

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

Example 1:
Input: x = 4
Output: 2
Explanation: The square root of 4 is 2, so we return 2.

Example 2:
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.

Constraints:
0 <= x <= 231 - 1

求平方根。

给你一个非负整数 x ,计算并返回 x 的 算术平方根 。

由于返回类型是整数,结果只保留 整数部分 ,小数部分将被 舍去 。

注意:不允许使用任何内置指数函数和算符,例如 pow(x, 0.5) 或者 x ** 0.5 。

思路

比较直观的思路就是线性扫描,但是这道题的考点/最优解应该是二分法。

二分法的具体做法是用 X/2 试试看是不是 X 的平方根。如果找不到(比如26就没有平方根),就输出最接近这个数平方根的那个整数。

影子题367,思路一模一样。

复杂度

时间O(logn), worse case O(n)
空间O(1)

代码

Java实现 - 这里为了处理整型越界问题,我把所有数字都改成long型再判断

class Solution {
    public int mySqrt(int x) {
        long left = 0;
        long right = x;
        while (left <= right) {
            long mid = left + (right - left) / 2;
            if (mid * mid == (long) x) {
                return (int) mid;
            } else if (mid * mid > (long) x) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        if (left * left < x) {
            return (int) left;
        }
        return (int) right;
    }
}

JavaScript实现

/**
 * @param {number} x
 * @return {number}
 */
var mySqrt = function(x) {
    // corner case
    if (x <= 0) {
        return 0;
    }

    // normal case
    let low = 1;
    let high = x;
    while (low <= high) {
        let mid = parseInt(low + (high - low) / 2);
        if (mid * mid === x) {
            return mid;
        } else if (mid * mid < x) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    if (high * high < x) {
        return high;
    } else {
        return low;
    }
};
posted @ 2019-10-18 00:36  CNoodle  阅读(507)  评论(0)    收藏  举报