[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/2 试试看是不是 X 的平方根。如果找不到(比如26就没有平方根),就输出最接近这个数平方根的那个整数。

影子题367,思路一模一样。

时间O(logn), worse case O(n)

空间O(1)

Java实现 - 这里为了处理整型越界问题,我把所有数字都改成long型再判断

 1 class Solution {
 2     public int mySqrt(int x) {
 3         long xx = x;
 4         long left = 1;
 5         long right = xx;
 6         while (left <= right) {
 7             long mid = left + (right - left) / 2;
 8             if (mid * mid == xx) {
 9                 return (int) mid;
10             } else if (mid * mid > xx) {
11                 right = mid - 1;
12             } else {
13                 left = mid + 1;
14             }
15         }
16         if (left * left < xx) {
17             return (int) left;
18         }
19         return (int) right;
20     }
21 }

 

JavaScript实现

 1 /**
 2  * @param {number} x
 3  * @return {number}
 4  */
 5 var mySqrt = function(x) {
 6     // corner case
 7     if (x <= 0) {
 8         return 0;
 9     }
10 
11     // normal case
12     let low = 1;
13     let high = x;
14     while (low <= high) {
15         let mid = parseInt(low + (high - low) / 2);
16         if (mid * mid === x) {
17             return mid;
18         } else if (mid * mid < x) {
19             low = mid + 1;
20         } else {
21             high = mid - 1;
22         }
23     }
24     if (high * high < x) {
25         return high;
26     } else {
27         return low;
28     }
29 };

 

LeetCode 题目总结

posted @ 2019-10-18 00:36  CNoodle  阅读(479)  评论(0编辑  收藏  举报