LeetCode --- 69. Sqrt(x)
来源:互联网 发布:js将字符串截取为数组 编辑:程序博客网 时间:2024/04/30 03:11
题目链接:Sqrt(x)
Implement int sqrt(int x).
Compute and return the square root of x.
这道题的要求是实现int sqrt(int x),即计算x的平方根。
考虑二分,即先令l和r分别为1和x/2+1(x的平方根一定小于等于x/2+1),然后m等于(l+r)/2,不断比较m*m和x的大小。
由于m*m的时候,可能溢出,因此可以用除法代替乘法,或者采用long long类型。
时间复杂度:O(logn)
空间复杂度:O(1)
1 class Solution{ 2 public: 3 int sqrt(int x) 4 { 5 if(x == 0) 6 return 0; 7 8 int l = 1, r = x / 2 + 1; 9 while(l <= r)10 {11 int m = (l + r) / 2;12 13 if(m <= x / m && m + 1 > x / (m + 1))14 return m;15 16 if(m > x / m)17 r = m - 1;18 else if(m < x / m)19 l = m + 1;20 }21 return l;22 }23 };
当然这题也可以采用位操作或者牛顿法。
转载请说明出处:LeetCode --- 69. Sqrt(x)
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)
- 关于Python的PIL工具的Image对象调用show()方法问题。
- date_format MYSQL
- 动态绑定遇到默认实参
- Climbing Stairs
- android开发之jni调用(java与c++相互调用)
- LeetCode --- 69. Sqrt(x)
- 都是自己走出来的路
- POJ 1543 Perfect Cubes
- 树型动态规划练习题:【bzoj1017】[JSOI2008]魔兽地图DotR
- MAC 下搭建Python分析环境 (安装 Enthought Canopy Express)
- LeetCode --- 70. Climbing Stairs
- Android自定义控件实战—滚动选择器PickerView(滚动变化字体)
- 2014134027谢天
- sqlite3 带占位符插入数据