题目:求平方根html
难度:Easygit
题目内容:算法
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.spa
翻译:翻译
计算并返回x的平方根,其中x保证是一个非负整数。code
因为退货类型是一个整数,因此小数部分被截断,而且只返回结果的整数部分。htm
Example 1:blog
Input: 4 Output: 2
Example 2:ip
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)
编程过程当中的问题:
一、由于mid在判断中也是判断过了的,不像Search in Rotated Sorted Array那样是等循环结束,因此left和right的下一个值都不须要再包括mid
答案代码:和个人同样。