69. Sqrt(x)
来源:互联网 发布:"笨办法"学python 编辑:程序博客网 时间:2024/06/10 03:15
Implement int sqrt(int x)
.
Compute and return the square root of x.
x is guaranteed to be a non-negative integer.
Example 1:
Input: 4Output: 2
Example 2:
Input: 8Output: 2Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.
这道题如果用暴力枚举法做会超时,所以要用时间复杂度更低的方法。
最容易的是二分法,每次都可以把查询范围缩小一半。注意这里为了防止溢出可以用long long:
class Solution {public: int mySqrt(int x) { long long i = 0, j = (x / 2) + 1; long long mid = (i + j) / 2; while (i <= j) { long long sqrt = mid * mid; if (sqrt == x) return mid; else if (sqrt < x) i = mid + 1; else j = mid - 1; mid = (i + j) / 2; } //这里肯定要return i和j里相对较小的那个,所以是j return j; }};
还有一个算法就是数值方法课讲过的牛顿迭代法。牛顿迭代法的思想和迭代公式可以参考百度百科。
这道题其实相当于给出n,求
可以根据递推式写出代码,注意这里先用double计算,最后再转成int:
class Solution {public: int mySqrt(int x) { if (x == 0) return 0; double last = 0; double pre = 1; while (pre != last) { last = pre; pre = (last + x / last) / 2; } return (int)pre; }};
阅读全文
0 0
- LeetCode 69. Sqrt(x)
- LeetCode 69.Sqrt(x)
- LeetCode --- 69. Sqrt(x)
- [Leetcode] 69. Sqrt(x)
- [leetcode] 69.Sqrt(x)
- 69.Sqrt(x)
- 69. Sqrt(x)
- Leetcode-69.Sqrt(x)
- leetcode--69.sqrt(x)
- 69. Sqrt(x)
- LeetCode 69. Sqrt(x)
- leetcode 69. Sqrt(x)
- 【LeetCode】69. Sqrt(x)
- 69. Sqrt(x) LeetCode
- 69. Sqrt(x)
- 69. Sqrt(x)
- [leetcode] 69. Sqrt(x)
- 69. Sqrt(x)
- 下载gradle地址
- Oracle 12c创建用户时为什么要在用户名前加”C##"?
- 责任链模式和状态模式对比
- 购物车的activity
- Spring Cloud Eureka 服务注册与发现
- 69. Sqrt(x)
- 85. Maximal Rectangle
- LeNet模型解读
- 在centos中安装了mysql5.7之后解决不知道随机的密码的问题
- Linux命令中:rsync和cp之间的区别
- <%=request.getContextPath()%>的作用
- [LeetCode] 264. Ugly Number II
- ThreadPoolExecutor
- 购物车的布局