当前位置:网站首页>【LeetCode-69】x的平方根
【LeetCode-69】x的平方根
2022-08-11 05:30:00 【Ring*】
10.2 x的平方根【69】
10.2.1 题目描述
给你一个非负整数 x ,计算并返回 x 的 算术平方根 。
由于返回类型是整数,结果只保留 整数部分 ,小数部分将被 舍去 。
注意:不允许使用任何内置指数函数和算符,例如 pow(x, 0.5) 或者 x ** 0.5 。

10.2.2 方法一:袖珍计算器算法

class Solution {
public int mySqrt(int x) {
if (x == 0) {
return 0;
}
int ans = (int) Math.exp(0.5 * Math.log(x));
return (long) (ans + 1) * (ans + 1) <= x ? ans + 1 : ans;
}
}
复杂度分析
- 时间复杂度:O(1),由于内置的 exp 函数与 log 函数一般都很快,我们在这里将其复杂度视为 O(1)。
- 空间复杂度:O(1)。
10.2.3 方法二:二分查找

class Solution {
public int mySqrt(int x) {
int l = 0, r = x, ans = -1;
while (l <= r) {
int mid = l + (r - l) / 2;
if ((long) mid * mid <= x) {
ans = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
return ans;
}
}
复杂度分析
- 时间复杂度:O(log x),即为二分查找需要的次数。
- 空间复杂度:O(1)。
10.2.4 my answer—二分查找
class Solution {
public int mySqrt(int x) {
int left = 0;
int right = x;
int ans = -1;
while (left<=right){
int mid = (left+right)/2;
if((long)mid*mid<=x){
ans = mid;
left = mid + 1;
}else{
right = mid - 1;
}
}
return ans;
}
}
边栏推荐
猜你喜欢

Day 85

Day 84

Day 82

js learning advanced (event senior pink teacher teaching notes)

8-byte standard request parsing during USB enumeration

Intelligent risk control China design and fall to the ground

Day 77

JS advanced web page special effects (pink teacher notes)

Interpretation of the paper: GAN and detection network multi-task/SOD-MTGAN: Small Object Detection via Multi-Task Generative Adversarial Network

The whole process of Tinker access --- Compilation
随机推荐
8-byte standard request parsing during USB enumeration
Byte (byte) and bit (bit)
精彩联动 | OpenMLDB Pulsar Connector原理和实操
星盟-pwn-babyfmt
JS小技巧,让你编码效率杠杠的,快乐摸鱼
深度学习Matlab工具箱代码注释
使用adb命令管理应用
Promise.race learning (judging the fastest execution of multiple promise objects)
OpenMLDB: Consistent production-level feature computing platform online and offline
星盟-pwn-fog
Jetpack使用异常问题集锦
C-8月1日-递归与动态内存管理
USB URB
[Meetup Preview] OpenMLDB+OneFlow: Link feature engineering to model training to accelerate machine learning model development
mongoose连接mongodb不错,显示encoding没有定义
手把手导入企业项目(快速完成本地项目配置)
欧拉法解微分方程
开发公众号授权遇到的redirect_uri参数错误
Fourth Paradigm OpenMLDB optimization innovation paper was accepted by VLDB, the top international database association
2021年vscode终端设置为bash模式