Problem Description
Implement the function int sqrt(int x).
Calculate and return the square root of x (rounded down)
Example
Example 1
Input
2
Output
1
Solutions
Ideas
- Dichotomy: three situations
mid * mid <= x && (mid + 1)*(mid + 1)> x: The square root meets the condition (because mid is an integer down here)
mid * mid <x: Take the left measurement space
mid * mid> x: Take the right measurement space
Code
// 思路1
public class Solution {
public int mySqrt(int x) {
int left = 1; int right = x;
while (true) {
int mid = (left + right) / 2;
if (mid <= x / mid && (mid + 1) > x / (mid + 1)) {
return mid;
} else if (mid < x / mid) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
}
Time complexity analysis:
O(lgN): dichotomy to traverse the array
Space complexity analysis:
O(1): No extra space is used
If you want to test, you can go directly to the link of Niuke.com to do the test