File tree Expand file tree Collapse file tree 2 files changed +33
-0
lines changed Expand file tree Collapse file tree 2 files changed +33
-0
lines changed Original file line number Diff line number Diff line change 26
26
55. 跳跃游戏
27
27
62. 不同路径
28
28
64. 最小路径和
29
+ 69. x 的平方根
29
30
70. 爬楼梯
30
31
72. 编辑距离
31
32
77. 组合
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments