【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)
Sqrt(x)
Implement int sqrt(int x).
Compute and return the square root of x, 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:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
/*
本题其实与分治法无关
方法:变形的二分查找法,找最后一个不大于目标值(x/mid)的数(由于返回整数,故可以用此方法)
*/
class Solution
{
public:
int mySqrt(int x)
{
if (x <= 1) return x;
int left = 0, right = x;
while (left < right)
{
int mid = left + (right - left) / 2;
if (mid <= (x/mid) )
left = mid + 1;
else
right = mid;
}
return right - 1; //通过返回right-1,改造返回第一个大于目标值(x/mid)的数 -> 返回最后一个不大于目标值的数
}
};
/*
方法二:牛顿迭代法
对于求方程f(x) = 0的根,可用迭代式 xk+1 = xk - f(xk)/f'(xk)进行求解
(特殊的简单迭代法xk+1 = p(xk),x = p(x)等价于f(x) = 0)
对此例x^2 = n,可推得xk+1 = (xk + n/xk)/2
*/
class Solution
{
public:
int mySqrt(int n)
{
if (n <= 1) return n;
double x = 1, x_pre = 0;
while (abs(x - x_pre) > 1e-6) //精度具体依题目要求
{
x_pre = x;
x = (x + n / x) / 2;
}
return int(x);
}
};