[LeetCode] 69. Sqrt(x) 求平方根


 

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since 
             the decimal part is truncated, 2 is returned.

 

這道題要求我們求平方根,我們能想到的方法就是算一個候選值的平方,然后和x比較大小,為了縮短查找時間,我們采用二分搜索法來找平方根,這里屬於博主之前總結的 LeetCode Binary Search Summary 二分搜索法小結 中的第三類的變形,找最后一個不大於目標值的數,這里細心的童鞋可能會有疑問,在總結貼中第三類博主的 right 用的是開區間,那么這里為啥 right 初始化為x,而不是 x+1 呢?因為總結帖里的 left 和 right 都是數組下標,這里的 left 和 right 直接就是數字本身了,一個數字的平方根是不可能比起本身還大的,所以不用加1,還有就是這里若x是整型最大值,再加1就會溢出。最后就是返回值是 right-1,因為題目中說了要把小數部分減去,只有減1才能得到正確的值,代碼如下:

 

解法一:

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

 

這道題還有另一種解法,是利用牛頓迭代法,記得高數中好像講到過這個方法,是用逼近法求方程根的神器,在這里也可以借用一下,可參見網友 Annie Kim's Blog的博客,因為要求 x2 = n 的解,令 f(x)=x2-n,相當於求解 f(x)=0 的解,可以求出遞推式如下:

xi+1=xi - (xi- n) / (2xi) = xi - xi / 2 + n / (2xi) = xi / 2 + n / 2xi = (xi + n/xi) / 2

 

解法二:

class Solution {
public:
    int mySqrt(int x) {
        if (x == 0) return 0;
        double res = 1, pre = 0;
        while (abs(res - pre) > 1e-6) {
            pre = res;
            res = (res + x / res) / 2;
        }
        return int(res);
    }
};

 

也是牛頓迭代法,寫法更加簡潔一些,注意為了防止越界,聲明為長整型,參見代碼如下:

 

解法三:

class Solution {
public:
    int mySqrt(int x) {
        long res = x;
        while (res * res > x) {
            res = (res + x / res) / 2;
        }
        return res;
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/69

 

類似題目:

Pow(x, n)

Valid Perfect Square

 

參考資料:

https://leetcode.com/problems/sqrtx/description/

https://leetcode.com/problems/sqrtx/discuss/25130/My-clean-C++-code-8ms

https://leetcode.com/problems/sqrtx/discuss/25047/A-Binary-Search-Solution

https://leetcode.com/problems/sqrtx/discuss/25057/3-4-short-lines-Integer-Newton-Every-Language

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM