题目链接

题意:就是求X的平方根。

思路:

方法一:

 

 

 注意:指数函数和对数函数的参数和返回值均为浮点数,因此运算过程中会存在误差。因此在得到结果的整数部分ans 后,我们应当找出ans 与 ans+1 中哪一个是真正的答案。

代码:

1 class Solution {
2     public int mySqrt(int x) {
3         if (x == 0) {
4             return 0;
5         }
6         int ans = (int) Math.exp(0.5 * Math.log(x));
7         return (long) (ans + 1) * (ans + 1) <= x ? ans + 1 : ans;
8     }
9 }

View Code

力扣官方的题解,感觉这样还不如直接pow或者sqrt。QAQ

方法二:二分

题目返回的是int型,也就是说答案是满足ans*ans ≤ x的ans最大值。所以,只需要在0~x范围内进行二分即可找到解。

代码:

class Solution {
public:
    int mySqrt(int x) {
        int l = 0, r = x, ans = -1;
        while (l <= r) {
            int mid = l + (r - l) / 2;
            if ((long long)mid * mid <= x) {
                ans = mid;
                l = mid + 1;
            } else {
                r = mid - 1;
            }
        }
        return ans;
    }
};

View Code

  • 时间复杂度:O(logx),即为二分查找需要的次数。

  • 空间复杂度:O(1)

方法三:牛顿迭代

待更。。。