版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85255202
Title:Sqrt(x) 69
Difficulty:Easy
原题leetcode地址: https://leetcode.com/problems/sqrtx/
1. 从1开始遍历,如果平方小于x,则继续,否则相等的话,直接返回i,否则大于,直接返回i-1(注意i*i可能溢出int)
时间复杂度:O(n),一次一层for循环。
空间复杂度:O(1),没有申请额外空间。
/**
* 从1开始遍历,如果平方小于x,则继续,否则相等的话,直接返回i,否则大于,直接返回i-1
* @param x
* @return
*/
public static int mySqrt(int x) {
if (x <= 0) {
return 0;
}
int result = 0;
for (long i = 1; i <= x / 2; i++) {
if (i * i < x) {
continue;
}
else {
if (i * i == x) {
result = (int)i;
break;
}
else {
result = (int)i - 1;
break;
}
}
}
return result;
}
2. 二分法,注意mid*mid可能溢出int
时间复杂度:O(logn),一次一层while循环。
空间复杂度:O(1),没有申请额外空间。
/**
* 二分法
* @param x
* @return
*/
public static int mySqrt1(int x) {
if (x <= 0) {
return 0;
}
int start = 0;
int end = x;
while (start <= end) {
long mid = (start + end) / 2;
if (mid * mid < x) {
start = (int)mid + 1;
}
else if (mid * mid > x) {
end = (int)mid - 1;
}
else {
return (int)mid;
}
}
return end;
}