LeetCode 0069 Sqrt(x)
作者:互联网
1. 题目描述
2. Solution
1、思路分析
二分查找,在[0, x]这个区间内执行二分查找,求mid,使得mid * mid = x。
2、代码实现
package Q0099.Q0069sqrtx;
/*
A Binary Search Solution from wikipedia:
https://en.wikipedia.org/wiki/Integer_square_root
*/
public class Solution {
public int mySqrt(int x) {
if (x == 0) return 0;
long lo = 0, hi = x;
while (lo < hi) {
long mid = (lo + hi + 1) / 2;
if (mid * mid > x) {
hi = mid - 1;
} else {
lo = mid;
}
}
return (int) lo;
}
}
3、复杂度分析
时间复杂度: O(log n)
空间复杂度: O(1)
3. Soution
1、思路分析
牛顿法
2、代码实现
package Q0099.Q0069sqrtx;
/*
Algorithm using Newton's method, from wikipedia
https://en.wikipedia.org/wiki/Integer_square_root
*/
public class Solution1 {
public int mySqrt(int x) {
long n = x;
while (n * n > x)
n = (n + x / n) / 2;
return (int) n;
}
}
3、复杂度分析
时间复杂度: O(log x)
空间复杂度: O(1)
标签:int,lo,复杂度,wikipedia,mid,Sqrt,hi,LeetCode,0069 来源: https://www.cnblogs.com/junstat/p/16184287.html