69 Sqrt(x)

对数法

由于计算机无法存储浮点数的精确值,指数函数和对数函数的参数和返回值均为浮点数,运运算过程中会存在误差,使得返回值有可能偏小。

  • 时间复杂度 O(1),空间复杂度O(1)
  • Runtime: 84 ms, faster than 98.21%
  • Memory Usage: 40.2 MB, less than 27.57%
/**
 * @param {number} x
 * @return {number}
 */
var mySqrt = function(x) {
    if (x === 0) return 0
    let res = parseInt(Math.exp(0.5 * Math.log(x)))
    return (res + 1) * (res + 1) <= x ? (res + 1) : res
};

二分查找

  • 时间复杂度O(logx),空间复杂度 O(1)
  • Runtime: 100 ms, faster than 60.84%
  • Memory Usage: 39.9 MB, less than 65.80%
/**
 * @param {number} x
 * @return {number}
 */
var mySqrt = function(x) {
    let res = -1
    let start = 0
    let end = x
    while(start <= end) {
        let mid = (start + end) >> 1
        let t = mid * mid
        if(mid * mid <= x) {
            res = mid
            start = mid + 1
        } else if(t > x) {
            end = mid - 1
        } 
    }
    return res
};

牛顿法

牛顿迭代法

  • 时间复杂度 O(logx),空间复杂度O(1),这个方法是二次收敛的,相对于二分查找更快
  • Runtime: 96 ms, faster than 74.28%
  • Memory Usage: 39.9 MB, less than 65.80%
/**
 * @param {number} x
 * @return {number}
 */
var mySqrt = function(x) {
    if(x === 0) return 0
    var cur = x
    while(cur > (cur + x / cur) / 2){
        cur = Math.abs((cur + x / cur) / 2)
    }
    return parseInt(cur)
};

你可能感兴趣的:(69 Sqrt(x))