LeetCode第[69]题(Java):Sqrt(x)

题目:求平方根

难度:Easy

题目内容

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

翻译

计算并返回x的平方根,其中x保证是一个非负整数。

由于退货类型是一个整数,所以小数部分被截断,并且只返回结果的整数部分。

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since 
             the decimal part is truncated, 2 is returned.

我的思路一个正整数(除了0和1)的平方根一定是从1到x/2,之间的某一个数,所以就相当于查找算法,所以采用二分法即可

    需要注意的是,我们的寻找条件,

  如果mid * mid > x   right = mid - 1;

  否则:此时mid * mid <= x,还满足,(mid+1) * (mid+1)> x 此时mid即可返回

     否则:left = mid +1;

我的代码

 1     public int mySqrt(int x) {
 2         if (x <= 1)
 3             return x;
 4         int left = 1, right = x/2;
 5         while (true) {
 6             int mid = left + (right - left)/2;
 7             if (mid > x/mid) {
 8                 right = mid - 1;
 9             } else {
10                 if (mid + 1 > x/(mid + 1))
11                     return mid;
12                 left = mid + 1;
13             }
14         }
15     }

我的复杂度:O(n)   

编程过程中的问题

1、因为mid在判断中也是判断过了的,不像Search in Rotated Sorted Array那样是等循环结束,所以left和right的下一个值都不需要再包括mid

 

 

答案代码:和我的一样。

posted on 2018-05-19 23:42  清风吹斜阳  阅读(374)  评论(0编辑  收藏  举报

导航