69 Sqrt(x)
69. Sqrt(x)
1. Question
Implementint sqrt(int x).
Compute and return the square root ofx.
x is guaranteed to be a non-negative integer.
Example 1:
Input: 4
Output:2Example 2:
Input: 8
Output: 2
Explanation:
The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will betruncated.2. Implementation
(1) Binary Search
思路:由于这题要求结果是整数,这就相当于找一个整数num <= sqrt(x), 是找右边界, 可以直接套用二分法的找右边界的模板
3. Time & Space Complexity
Binary Search: 时间复杂度O(logx), 空间复杂度O(1)
Last updated
Was this helpful?