leetcode -- Binary search (5)

Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

解法1:二分法。先进行猜测,然后不断逼近。

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


解法2:牛顿法。利用泰勒级数展开,求多项式函数的近似解。机器学习中梯度下降也常用到牛顿法求近似最优解。牛顿法详细解释: http://www.guokr.com/question/461510/

    int mySqrt(int x) {
        long k = x;
        while (k * k > x){
            k = (k + x / k) / 2;
        }
        return k;
    }


Pow(x, n)

解法1:类似Division的策略。二分查找+D&C

    double myPow(double x, int n) {
        double rst = 1;
        long an = labs(n);  //这里必须用long,否则n=-2147483648时会越界,因为abs(INT_MIN) = INT_MAX + 1
        while (an > 0){
            double tmp = x;
            long p2 = 1;
            while ((p2 << 1) <= an){
                p2 <<= 1;
                tmp *= tmp; 
            }
            an -= p2;
            rst *= tmp;
        }
        return n > 0 ? rst : 1 / rst;
    }

解法2:递归。感觉这个应该更快一些,因为每个x的指数只被计算了一次。尽可能的使用了已有的结果。

double myPow(double x, int n) { 
    if(n==0) return 1;
    double t = myPow(x,n/2);
    if(n%2) return n<0 ? 1/x*t*t : x*t*t;
    else return t*t;
}

其他解法:https://discuss.leetcode.com/topic/21837/5-different-choices-when-talk-with-interviewers/2

你可能感兴趣的:(leetcode)