sqrtx
来源:互联网 发布:哪个清理软件最好 编辑:程序博客网 时间:2024/06/06 23:45
题目:
Implementint sqrt(int x).
Compute and return the square root of x.
程序:
class Solution {public: int sqrt(int x) {//思路用二分法 if (x < 2) return x; int left = 1, right = x / 2; //右端从x/2开始 int mid, last_mid; while (left <= right) { mid = left + (right - left) / 2; if (x / mid > mid) { //不用x > mid * mid 会溢出 left = mid + 1; last_mid = mid; } else if (x / mid < mid) right = mid - 1; else return mid; } return last_mid; }};
点评:
采用二分法,两端逼近,在做连续序列或者数组类题目时,可用二分法减少时间复杂度
阅读全文
0 0
- sqrtx
- 【leetcode】sqrtx
- leetcode:sqrtx
- LeetCode069 sqrtx java solution
- 4.26 leetcode -26 sqrtx
- leetcode---sqrtx---分治
- Lintcode141 Sqrtx solution 题解
- https://leetcode.com/problems/sqrtx/
- 二分查找——sqrtx
- Leecode题集——sqrtx
- Springboot系列:Springboot与Thymeleaf模板引擎整合基础教程(附源码)
- 【兴趣书签】喜欢的SOHO家居布局
- Python学习笔记-17.09.15
- Remove Element
- USTCOJ 1127 Laser in Cuboids (思路+容斥原理)
- sqrtx
- oracle日期转换
- 流运算符为什么不能重载为成员函数,只能用友元函数重载
- bzoj 4026: dC Loves Number Theory 可持久化线段树
- EL表达式详解
- 在Mac上安装TensorFlow
- 使用Sublime Text 3编辑markdown
- C语言——自定义头文件
- Spring AOP面向切面编程