普通方法简单但超时
二分
常规手段了
class Solution {
public:
bool isPerfectSquare(int num) {
long l = 1, r = num, mid, guess;
while(l <= r){
mid = l + (r-l)/2;
guess = mid*mid;
if(guess == num) return true;
if(guess > num) r = mid - 1;
else l = mid + 1;
}
return false;
}
};
牛顿迭代法
解释可以看题解:
有效的完全平方数 - 有效的完全平方数 - 力扣(LeetCode)
本题就是寻找 x^2 - num = 0的 x。
class Solution {
public:
bool isPerfectSquare(int num) {
if(num == 1) return true;
long x = num/2;
while(x*x > num){
x = (x + num/x)/2;
}
return x*x == num;
}
};
累加奇数
完全平方数可以通过累加从1往后的奇数找到:
1 = 1;
4 = 1 + 3;
9 = 1 + 3 + 5;
16 = 1 + 3 + 5 + 7;
…
证明: 假设n>=2 则: (n+1)^2 - n^2=(n+1-n)(n+n+1) = 2n+1
即:
A
n
+
1
=
A
n
+
2
n
+
1
A_{n+1}=A_{n}+2n+1
An+1=An+2n+1
=
A
n
−
1
+
(
2
n
−
1
)
+
(
2
n
+
1
)
=A_{n-1} + (2n-1)+(2n+1)
=An−1+(2n−1)+(2n+1)
=
1
+
3
+
.
.
.
2
n
+
1
=
(
n
+
1
)
2
= 1+3+...2n+1=(n+1)^2
=1+3+...2n+1=(n+1)2
class Solution {
public:
bool isPerfectSquare(int num) {
int i = 1;
while(num > 0){
num -= i;
i += 2;
}
return num == 0;
}
};