当前位置:网站首页>二分查找2 - x的平方根
二分查找2 - x的平方根
2022-08-03 05:25:00 【花开花落夏】
x 的平方根
一 题目
给你一个非负整数 x ,计算并返回 x 的算术平方根 。由于返回类型是整数,结果只保留整数部分 ,小数部分将被舍去 。
注意:不允许使用任何内置指数函数和算符,例如 pow(x, 0.5) 或者 x ** 0.5 。
来源:leetcode官网
二 解题
非负整数x的算术平方根target,必然0<=target<=x,可以使用二分法来求target。
若mid*mid<=x,则说明target在[mid+1,right]之间,否则target在[left,mid-1]之间。
class Solution {
public int mySqrt(int x) {
int left = 0, right = x, mid;
int index = -1;
while(left<=right){
mid=(left+right)/2;
if((long)mid*mid<=x){
index=mid;
left=mid+1;
}else{
right=mid-1;
}
}
return index;
}
}

边栏推荐
猜你喜欢
MMU 介绍-[TBL/page table work]

MATLAB自带的dwt2和wavedec2函数实现基于小波变换的自适应阈值图像边缘检测

2021-03-22

自监督论文阅读笔记 Self-Supervised Deep Learning for Vehicle Detection in High-Resolution Satellite Imagery

Dynamic adjustment subject web system?Look at this one is enough

【第二周】卷积神经网络

pandoc -crossref插件实现markdwon文档转word后公式编号自定义

2021-03-22

IPC通信 - 管道

【第三周】ResNet+ResNeXt
随机推荐
ASP.NET MVC3的伪静态实现
自监督论文阅读笔记 Self-supervised Learning in Remote Sensing: A Review
常见的电子元器件分类介绍
【第三周】ResNet+ResNeXt
window下VS2022封装动态库以及调用动态库
block底层探索
A.1#【内存管理】——1.1.1 node:struct pglist_data
double型数据转字符串后通过MCU串口发送
三、final、finally、 finalize有什么不同?
POE交换机全方位解读(中)
西塞罗 论老年
ZEMAX | 在OpticStudio中建立扩增实境(VR)头戴式显示器
自监督论文阅读笔记FIAD net: a Fast SAR ship detection network based on feature integration attention and self
ZEMAX | 在 OpticStudio 中使用自由曲面进行设计
servlet学习(七)ServletContext
自监督论文阅读笔记 Self-Supervised Visual Representation Learning with Semantic Grouping
六、对比Vector、ArrayList、LinkedList有何区别?(设计、性能、安全)
二阶段提问总结
C# 数组之回溯法
梯度下降、反向传播