Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

二分法

思路

一个数x的平方根m满足mm <= x < (m+1)(m+1)
用二分法查找m的值

复杂度

时间O(logn) 空间O(1)

代码

public int mySqrt(int x) {
    if (x < 0 || x == 0) {
        return 0;
    } 
    int left = 1, right = x;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (x / mid >= mid  && x / (mid + 1) < mid + 1 ) {
            return mid;
        } else if (x / mid < mid) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return 0;
}

Pow(x, n)

递归法

复杂度

时间O(logn) 空间栈O(logn)

代码

public double myPow(double x, int n) {
    if (n < 0) {
        return 1/ helper(x, - n);
    } else {
        return helper(x, n);
    }
}
public double helper(double x, int n) {
    if (n == 0) {
        return 1.0;
    } else if (n == 1) {
        return x;
    }
    double m = helper(x, n / 2);
    if (n % 2 == 1) {
        return m* m * x;
    } else {
        return m * m;
    }
}

lpy1990
26 声望10 粉丝