Lintcode141 Sqrtx solution 题解
2017-10-09 23:43
363 查看
【题目描述】
Implement intsqrt(int x).
Compute and return the square root ofx.
实现int sqrt(int x)函数,计算并返回x的平方根。
【题目链接】
www.lintcode.com/en/problem/sqrtx/
【题目解析】
问题可以转化为从1 ~ x寻找目标数字,于是二分法就可以提供O(log(n))的时间复杂度,O(1)的空间复杂度。
此外,可以考虑使用牛顿法:x_(n+1) = x_n - f(x_(n))/f'(x_(n))
其中S 满足 x = sqrt(S),f(x_(n)) = (x_(n)) ^ 2 - S
于是x_(n+1) = x_(n) - ((x_(n))^ - S) / (2 * x_(n)) = 1/2 * (x_(n) + S / x_(n))
这样只需迭代x_(n+1) = 1/2 * (x_(n) + S/x_(n)),
直到| x_(n+1) - x_(n) | < 1
【参考答案】
www.jiuzhang.com/solutions/sqrtx/
Implement intsqrt(int x).
Compute and return the square root ofx.
实现int sqrt(int x)函数,计算并返回x的平方根。
【题目链接】
www.lintcode.com/en/problem/sqrtx/
【题目解析】
问题可以转化为从1 ~ x寻找目标数字,于是二分法就可以提供O(log(n))的时间复杂度,O(1)的空间复杂度。
此外,可以考虑使用牛顿法:x_(n+1) = x_n - f(x_(n))/f'(x_(n))
其中S 满足 x = sqrt(S),f(x_(n)) = (x_(n)) ^ 2 - S
于是x_(n+1) = x_(n) - ((x_(n))^ - S) / (2 * x_(n)) = 1/2 * (x_(n) + S / x_(n))
这样只需迭代x_(n+1) = 1/2 * (x_(n) + S/x_(n)),
直到| x_(n+1) - x_(n) | < 1
【参考答案】
www.jiuzhang.com/solutions/sqrtx/
相关文章推荐
- 剑指offer 面试题18: 树的子结构(LintCode 245.Subtree) 题解
- Lintcode155 Minimum Depth of Binary Tree solution 题解
- LintCode题解之子树
- lintcode: Sqrt(x)
- lintcode-x的平方根-141
- Lintcode190 Next Permutation II solution 题解
- Sqrt(x) - LintCode
- [LeetCode]题解(python):141-Linked List Cycle
- lintcode-141 x的平方根
- [LintCode]sqrt(x)
- [LintCode] 586 Sqrt(x) II 解题报告
- Lintcode 74 First Bad Version solution 题解
- LintCode 数字组合 题解
- #141 Sqrt(x)
- Lintcode156 Merge Intervals solution 题解
- LeetCode题解:Sqrt(x)
- LintCode题解之比较字符串
- 【LeetCode题解】141_环形链表
- [Lintcode]Sqrt(x)
- LeetCode 141 Linked List Cycle题解