<= x,采用二分法求出(1, x) 之间a最大值。
- public int mySqrt(int x) {
- int low = 0;
- int height = x;
- int mid = (low + height) / 2;
- while (low <= height) {
- if ((long) mid * mid - x > 0) {
- height = mid - 1;
- } else {
- low = mid + 1;
- }
- mid = (low + height) / 2;
- }
-
- return mid;
- }
注意:mid * mid 可能会超出 int 上限,需要转化为 long。
时间复杂度:O(logn)