Description:
Given a non-negative integer c, your task is to decide whether there’re two integers a and b such that a2 + b2 = c.
Example 1:
Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3
Output: False
题意:给定一个非负数 c c c,计算是否存在整数 a a a和 b b b,使得 a 2 + b 2 = c a^2 + b^2 = c a2+b2=c;
解法一(超时):最简单的办法就是使用暴力求解, a a a和 b b b的取值区间在 [ 0 , c 1 / 2 ] [0, c^{1/2}] [0,c1/2];最终肯定会超时的;
Java
class Solution {
public boolean judgeSquareSum(int c) {
for (long a = 0; a * a <= c; a++) {
for (long b = 0; b * b <= c; b++) {
if (a * a + b * b == c) {
return true;
}
}
}
return false;
}
}
解法二:对公式变形得到 b 2 = c − a 2 b^2 = c - a^2 b2=c−a2,因此我们只需要在区间 [ 0 , c 1 / 2 ] [0, c^{1/2}] [0,c1/2]内寻找是否由满足条件的 b b b即可;这里我们利用二分查找来实现快速的查找;
Java
class Solution {
public boolean judgeSquareSum(int c) {
for (long a = 0; a * a <= c; a++) {
long b = c - a * a;
if (find(0, b, b)) {
return true;
}
}
return false;
}
private boolean find(long low, long high, long target) {
if (low > high) {
return false;
}
while (low <= high) {
long mid = low + (high - low) / 2;
if (mid * mid == target) {
return true;
} else if (mid * mid > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return false;
}
}