Sqrt(x)--LeetCode
来源:互联网 发布:mac 终端显示完整路径 编辑:程序博客网 时间:2024/05/17 04:15
1.题目
Sqrt(x)
Implement int sqrt(int x).
Compute and return the square root of x.
2.题意
实现 int sqrt (int x)
计算并返回 x 的平方根
3.分析
1)二分法,基本思路与二分查找类似
取定左值和右值,每次砍掉不符合条件的一半,直到左值和右值相遇
时间复杂度是O(logx),空间复杂度是O(1)
注意x<2不要写成x<=2,left<=right不要写成left<=right
2)也可采用牛顿迭代法
4.代码
class Solution {public: int mySqrt(int x) { if(x < 2) return x; int res = 0; int left = 0; int right = x / 2 + 1; while(left <= right) { int mid = left + (right - left) / 2; if(x / mid > mid) { left = mid + 1; res = mid; } else if(x / mid < mid) right = mid - 1; else return mid; } return res; }};
阅读全文
0 0
- LeetCode: Sqrt(x)
- LeetCode sqrt(x)
- [Leetcode] Sqrt(x)
- LeetCode :Sqrt(x)
- leetcode 53: Sqrt(x)
- [LeetCode] Sqrt(x)
- Leetcode 69 sqrt(x)
- [Leetcode] Sqrt(x)
- leetcode:Sqrt(x)
- 【leetcode】sqrt(int x)
- [LeetCode]Sqrt(x)
- [leetcode]Sqrt(x)
- LeetCode-Sqrt(x)
- [leetcode] Sqrt(x)
- [leetcode] Sqrt(x)
- LeetCode - Sqrt(x)
- leetcode之sqrt(x)
- LeetCode | Sqrt(x)
- 面试_Java知识总架构
- [论文解读] Monocular 3D Object Detection for Autonomous Driving Xiaozhi
- 设计模式之模板模式(1)
- [论文解读] Pedestrian Detection Combining RGB and Dense LIDAR Data
- C语言学习笔记——排序
- Sqrt(x)--LeetCode
- 前端编码规范及 SASS、SCSS和CSS的关系
- 常用js正则表达式
- maven基础学习
- 打招呼
- 线段树的建立、查询、更新及应用
- HDU 5113 Black And White(DFS)
- PAT 1007.素数对猜想(20)
- Ubuntu 下进制自动挂载 Android MTP