Sqrt(x)
Implementint sqrt(int x)
.
Compute and return the square root ofx, 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:
Example 2:
Analysis
Binary Search
Typical binary search problem (although better way could be Newton's method)
Tips:
use mid == x / mid
to avoid overflow
right
is the closest, since before the last loop, it was left = mid = right
Newton
x_(n+1) = x_(n) - f(x_n) / f'(x_(n))
For the sqrt(x) function, it's actually:
f(x) = x^2 - y
f'(x) = 2 * x
Then x(n+1) = x(n) - [x(n) ^ 2 - y] / [2 * x(n)]
Simplified:
x(n+1) = [x(n) + y / x(n)] / 2
Solution
Using binary search basic template #1
Source: https://leetcode.com/problems/sqrtx/discuss/25047/A-Binary-Search-Solution/24042
The sequence
1, 2, ... , n
has no duplication.Near the very end, closest step, before
while
loop,left = mid = right
.In
while
, Ifmid < sqrt(x)
,left = mid + 1
executed,right
pointer is not moving, andright
is the answer.If
while
, Ifmid > sqrt(x)
,right = mid - 1
executed,right
pointer shifts left1
, closest tosqrt(x)
,right
is also the answer.
Last updated