当前位置:网站首页>【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;
}
}
边栏推荐
- Compilation exception resolution
- jdbc接口文档参考,jdbc接口方法逻辑探究
- 连接数据库时出现WARN: Establishing SSL connection without server‘s identity verification is not recommended.
- 本地缓存cookie的使用
- Day 78
- Day 69
- 构建面向特征工程的数据生态 ——拥抱开源生态,OpenMLDB全面打通MLOps生态工具链
- C language implementation guess Numbers (with source code, can be directly run)
- 自己动手写RISC-V的C编译器-01实现加减法
- C语言-7月21日-指针的深入
猜你喜欢
随机推荐
vim 编辑器使用学习
解决AttributeError: ‘NoneType‘ object has no attribute ‘val‘ if left.val!=right.val:Line 17 问题
ARM assembly instruction ADR and LDR
USB URB
Jetpack use exception problem collection
[Meetup]OpenMLDBxDolphinScheduler 链接特征工程与调度环节,打造端到端MLOps工作流
JS案例练习(pink老师经典案例)
活动预告 | 4月23日,多场OpenMLDB精彩分享来袭,不负周末好时光
Use the adb command to manage applications
The whole process of Tinker access --- configuration
本地服务配置内网穿透实现微信公众号整合
mk文件介绍
开发公众号授权遇到的redirect_uri参数错误
The mount command - mounted read-only, solution
父子节点数据格式不一致的树状列表实现
字节(byte)和位(bit)
2022DASCTF X SU 三月春季挑战赛 checkin ROPgadget进阶使用
Minutes of OpenMLDB Meetup No.2
欧拉法解微分方程
PAT乙级刷题之路








