版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/89459783
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
题意:给定一个非负数 ,计算是否存在整数 和 ,使得 ;
解法一(超时):最简单的办法就是使用暴力求解, 和 的取值区间在 ;最终肯定会超时的;
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;
}
}
解法二:对公式变形得到 ,因此我们只需要在区间 内寻找是否由满足条件的 即可;这里我们利用二分查找来实现快速的查找;
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;
}
}