69. Sqrt(x)
注意 range 是 1 ~ x, 要找平方根
left ~ right: 1~x
finally, return right
A little trick is using i <= x / i for comparison,
instead of i * i <= x, to avoid exceeding integer upper limit.
Binary Search Solution:
Time complexity = O(lg(x)) = O(32)= O(1) (log(2^32) = 32)
space: O(1) public int mySqrt(int x) {
int left = 1; //1~x
int right = x;
while (left <= right) {
int mid = left + (right - left) / 2; // (left + right) >>> 1
if (mid == x / mid) { // 4 8/4=2
return mid;
} else if (mid < x / mid) {
left = mid + 1;
} else {
right = mid - 1; //3
}
}
return right; // in the end, right must < left, so ans is right
}另一種思路
https://leetcode-cn.com/problems/sqrtx/solution/er-fen-cha-zhao-niu-dun-fa-python-dai-ma-by-liweiw/
new style
use x/mid, 但要注意 edge case (0,1)
use 乘法, 但要 long, 不然會溢位
Last updated
Was this helpful?