leetcode:69. Sqrt(x)
来源:互联网 发布:linux home空间 编辑:程序博客网 时间:2024/06/10 02:27
描述
Implement int sqrt(int x).
Compute and return the square root of x.
思路
使用二分法搜索。
这里我一开始犯了这么一个错误,mid*mid很容易超过计算机能够表示的阈值,这里只要把转换成mid与x/mid比较就好了
代码
class Solution {public: int mySqrt(int x) { if (x == 0) return 0; int left = 1, right = INT_MAX; while (true) { int mid = left + (right - left)/2; if (mid > x/mid) { right = mid - 1; } else { if (mid + 1 > x/(mid + 1)) return mid; left = mid + 1; } } }};
结果
他山之玉
C++ O(n) solutioin
long r = x; while (r*r > x) r = (r + x/r) / 2; return r;
Java O(n) solution
public int mySqrt(int x) { if (x < 1) return x; int lo = 1, hi = x, mid = 0; while (lo <= hi){ mid = (hi - lo) / 2 + lo; if (mid > x / mid) hi = mid - 1; else if (mid < x / mid) lo = mid + 1; else return mid; } return hi; }
python O(n) solution
class Solution(object): def mySqrt(self, x): return int(x**(1/float(2)))
这个思路应该算作弊吧,不过厉害了
0 0
- LeetCode 69. Sqrt(x)
- LeetCode 69.Sqrt(x)
- LeetCode --- 69. Sqrt(x)
- [Leetcode] 69. Sqrt(x)
- [leetcode] 69.Sqrt(x)
- Leetcode-69.Sqrt(x)
- leetcode--69.sqrt(x)
- LeetCode 69. Sqrt(x)
- leetcode 69. Sqrt(x)
- 【LeetCode】69. Sqrt(x)
- 69. Sqrt(x) LeetCode
- [leetcode] 69. Sqrt(x)
- leetcode 69. Sqrt(x)
- LeetCode 69. Sqrt(x)
- LeetCode 69. Sqrt(x)
- leetcode-69. Sqrt(x)
- [leetcode]69. Sqrt(x)
- LeetCode-69.Sqrt(x)
- 如何查看和清除Windows本地的DNS缓存内容
- 算法原理 第七章 快速排序
- Java类加载过程
- Linux中启动Tomcat:bash: ./startup.sh: Permission denied问题
- MemCache超详细解读
- leetcode:69. Sqrt(x)
- 在 C# 中使用 C++
- MySQL索引的使用
- 第6天HBase笔记
- 关于SurfaceView横竖屏切换显示问题
- iOS 基于环信SDK实现即时通讯-文字聊天
- Apache Thrift 配置和使用指南
- selenium 如何获取分页数据
- Retrofit2学习笔记-1