LeetCode:69. Sqrt(x)
2017-03-05 22:34
459 查看
题目链接:
69. Sqrt(x)题目描述:
Implement int sqrt(int x)Compute and return the square root of x.
题目解释:
提干非常简单,就是实现一个整数的求平方根的函数,输入为int,输出也是int。解题方案:
求一个整数的平方根,最土的办法是从0开始尝试0,1,2,3,4…判断是不是数x的平方根,但是这种方式的时间复杂度为O(n),是线性时间的,特别是运算过程中会有一个乘积需要计算,时间复杂度不符合要求,会超时。我们仔细前文最土求平方根的方式可以看到,整数x的平方根是有序数列0,1,2,3,4,5…….n中的一员,求平方根其实就是在这个有序数列[0,n]中查找出来某一个数,这样我们就把求根问题转换为了查找问题。在有序数组中查找的高效解法为:二分查找。另外这里有个要注意的点:在最土办法中,我们使用数k的平方与x比较,从而判断是不是平方根,而二分法是不行的,因为二分法的查找不再是从小到大。第一个二分点的乘积可能会超过整数的表示范围。所以我们需要将乘法变换为除法,利用(x / mid) / mid == 0 这样的方式来判断x与 中点mid * mid乘积的大小。
AC代码:
class Solution { public: int mySqrt(int x) { if ( x == 0 ) return 0; int low = 0; int high = x; int root = 0; while(low <= high) { int mid = (low + high) / 2; //刚好找到平方根,直接放回结果。 if ( (mid != 0) && (x / mid) / mid == 0 ) { //mid * mid > x 的场景 //平方根在左侧,需要在左侧递归 high = mid - 1; } else { if ( mid * mid == x ) { return mid; } if ( mid * mid < x ) { //假设根为 当前mid,利用这种方式寻求平方和小于x的最大整数 root = mid; //平方根在右侧 low = mid + 1; } } } return root; } };
相关文章推荐
- Leetcode 69. Sqrt(x)
- Leetcode 69. Sqrt(x)
- [leetcode 69] Sqrt(x)
- LeetCode 第 69 题 (Sqrt(x))
- LeetCode【69】 Sqrt(x)
- leetcode 69. Sqrt(x)
- [Leetcode] 69. Sqrt(x) 解题报告
- Leetcode-69: Sqrt(x)
- Leetcode 69. Sqrt(x) (Easy)
- [leetcode:python]69.Sqrt(x)
- leetcode-69. Sqrt(x)
- LeetCode 69. Sqrt(x)
- LeetCode 69. Sqrt(x)
- LeetCode 69: Sqrt(x)
- 【LeetCode】(69)Sqrt(x)(Medium)
- [LeetCode]69 Sqrt(x)
- 个人记录-LeetCode 69. Sqrt(x)
- 【leetcode】【69】Sqrt(x)
- LeetCode 69 Sqrt(x)(Math、Binary Search)(*)
- LeetCode-69-Sqrt(x) Python要用math.sqrt()