Skip to content

Commit 0342167

Browse files
committed
69.x的平方根,二分查找
1 parent c408248 commit 0342167

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

leetcode_Java/DoneTitle.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
55. 跳跃游戏
2727
62. 不同路径
2828
64. 最小路径和
29+
69. x 的平方根
2930
70. 爬楼梯
3031
72. 编辑距离
3132
77. 组合

leetcode_Java/Solution0069.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// 69. x 的平方根
2+
3+
4+
/*
5+
二分查找:
6+
1、while条件left<=right,等号要加上,包含了x=0的情况时left==right
7+
2、每次找到中点,比较 中点的平方 与 x 的大小,决定区间缩小的方向
8+
3、返回值小数会被省去,中点 可能刚好是目标值 或 可能就是最后一个平方小于x的值,所以每次都要保存中点防止丢失
9+
4、中点的平方可能数值较大,超过int范围导致溢出,所以需要先强转为long类型再计算,比较大小时x自动从int类型向上转型为long类型
10+
*/
11+
class Solution {
12+
public int mySqrt(int x) {
13+
int left = 0, right = x, res = -1;
14+
while (left <= right) {
15+
int mid = (left + right) / 2;
16+
if ((long) mid * mid <= x) {
17+
res = mid;
18+
left = mid + 1;
19+
} else {
20+
right = mid - 1;
21+
}
22+
}
23+
return res;
24+
}
25+
}
26+
27+
28+
class Solution {
29+
public int mySqrt(int x) {
30+
return (int) Math.pow(x, 0.5);
31+
}
32+
}

0 commit comments

Comments
 (0)