当前位置:网站首页>【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 70
- 开源之夏 2022 火热来袭 | 欢迎报名 OpenMLDB 社区项目~
- 详解程序执行过程
- Compilation exception resolution
- C-8月1日-递归与动态内存管理
- Jetpack's dataBinding
- Wonderful linkage | OpenMLDB Pulsar Connector principle and practical operation
- 一文看懂注解与反射
- Use the adb command to manage applications
- Regular expression replacement for batch quick modification code
猜你喜欢

第六届蓝帽杯 EscapeShellcode

经纬度求距离

Event Preview | On April 23, a number of wonderful sharing sessions of OpenMLDB will come, which will live up to the good time of the weekend

自己动手写RISC-V的C编译器-02语法描述方法和递归下降解析

开发公众号授权遇到的redirect_uri参数错误

buuctf hacknote

IO流和序列化与反序列化

C语言-7月22日- NULL和nullptr的深入了解以及VScode对nullptr语句报错问题的解决

Manufacturer Push Platform-Huawei Access

Tinker的自我介绍
随机推荐
Day 80
Event Preview | On April 23, a number of wonderful sharing sessions of OpenMLDB will come, which will live up to the good time of the weekend
Jetpack使用异常问题集锦
C语言-7月18日-二维数组的学习
OpenMLDB v0.5.0 released | Performance, cost, flexibility reach new heights
黑马大事件项目
The Summer of Open Source 2022 is coming | Welcome to sign up for the OpenMLDB community project~
将一个excel文件中多个sheet页“拆分“成多个“独立“excel文件
Promise.race learning (judging the fastest execution of multiple promise objects)
深度学习Matlab工具箱代码注释
The whole process of Tinker access --- Compilation
JVM tuning and finishing
字节(byte)和位(bit)
自己动手写RISC-V的C编译器-02语法描述方法和递归下降解析
The whole process of Tinker access --- configuration
Day 76
本地服务配置内网穿透实现微信公众号整合
Day 83
【无标题】
C语言实现扫雷游戏