Leecode题集——sqrtx
来源:互联网 发布:程序员查工资的网站 编辑:程序博客网 时间:2024/06/03 14:28
Implementint sqrt(int x).
Compute and return the square root of x.
直接遍历会超时,有两种方法:一是二分查找法,二是牛顿迭代法。
方法一、二分查找法
int sqrt(int x){ //鲁棒性检查,不合理输入 if(x<0) return -1; if(x==0) return 0; //确定搜索范围 long long i=0; long long j=x/2+1; while(i<=j) { long long mid=(i+j)/2; long long sq=mid*mid; if(sq<x) i=mid+1; else if(sq>x) j=mid-1; else return mid; } return j;}方法二、牛顿迭代法
为了方便理解,就先以本题为例:
计算x2 = n的解,令f(x)=x2-n,相当于求解f(x)=0的解,如右图所示。
首先取x0,如果x0不是解,做一个经过(x0,f(x0))这个点的切线,与x轴的交点为x1。
同样的道理,如果x1不是解,做一个经过(x1,f(x1))这个点的切线,与x轴的交点为x2。
以此类推。
以这样的方式得到的xi会无限趋近于f(x)=0的解。
判断xi是否是f(x)=0的解有两种方法:
一是直接计算f(xi)的值判断是否为0,二是判断前后两个解xi和xi-1是否无限接近。
经过(xi, f(xi))这个点的切线方程为f(x) = f(xi) + f’(xi)(x - xi),其中f'(x)为f(x)的导数,本题中为2x。令切线方程等于0,即可求出xi+1=xi - f(xi) / f'(xi)。
继续化简,xi+1=xi - (xi2 - n) / (2xi) = xi - xi / 2 + n / (2xi) = xi / 2 + n / 2xi = (xi + n/xi) / 2。
int sqrt(int x) { if(x<0) return -1; if(x==0) return 0; double last=0; double res=1; while(last!=res) { last=res; res=(res+x/res)/2; } return (int)res; }当输入为double类型时,
double sqrt(double x){ if(x=0.0) return 0.0; double last=0.0; double res=1.0; while(last!=res) { last=res; res=(res+x/res)/2; } return res;}
0 0
- Leecode题集——sqrtx
- 二分查找——sqrtx
- sqrtx
- Leecode记录——Valid Palindrome
- [LeeCode]—Wildcard Matching 通配符匹配问题
- 【leetcode】sqrtx
- leetcode:sqrtx
- leecode
- LeeCode
- 每天一道算法题——Leecode.386. Lexicographical Numbers
- LeetCode069 sqrtx java solution
- 4.26 leetcode -26 sqrtx
- leetcode---sqrtx---分治
- Lintcode141 Sqrtx solution 题解
- https://leetcode.com/problems/sqrtx/
- Leecode 记录——Remove Nth Node From End of List
- 每天一道算法题——LeeCode.387. First Unique Character in a String
- 每天一道算法题——LeeCode.389. Find the Difference
- #114 Unique Paths
- **YII** 系列十一应用结构中的模块
- Head First 观察者模式
- 在shell脚本里使用sftp批量传送文件
- 2016 Personal Training #11 Div.2 B G J
- Leecode题集——sqrtx
- HDU.4605 Magic Ball Game
- MPTCP 源码分析(0) MPTCP 理解
- Activiti(二)——部署流程资源的三种方式
- 基于tcl tk 的HyperView二次开发实例【2】
- hdu 5807 Keep In Touch
- 《一个操作系统的实现》学习笔记6
- 搭建linux下的深度学习开发环境
- HDU 1879 继续畅通工程-最小生成树