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的平方根,然后用two pointer上下看到底能不能找到这个平方根。如果找不到(比如26就没有平方根),就输出最接近这个数平方根的那个整数。
影子题367,思路一模一样。
时间O(log n), worse case O(n)
空间O(1)
Java实现
1 class Solution { 2 public int mySqrt(int x) { 3 // corner case 4 if (x == 0) { 5 return 0; 6 } 7 8 // normal case 9 int low = 1; 10 int high = x; 11 while (low <= high) { 12 long mid = low + (high - low) / 2; 13 if (mid * mid == x) { 14 return (int) mid; 15 } else if (mid * mid < x) { 16 low = (int) mid + 1; 17 } else { 18 high = (int) mid - 1; 19 } 20 } 21 if (high * high < x) { 22 return (int) high; 23 } else { 24 return (int) low; 25 } 26 } 27 }
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 };