https://leetcode.com/problems/sum-of-square-numbers/
给定一个非负整数c,找到两个整数a、b使得a*a + b*b = c*c,如果存在则返回true,如果不存在则返回false
一、问题分析
测试用例:
Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
Input: 3
Output: False
虽然这里没有要求两个整数必须是非负整数,但是由于(-a)^2 = (a)^2,因此我们这里其实不用考虑两个整数为负数的情况,所以我们将a、b视为非负整数。而要使得a^2 + b^2 = c^2,a、b的平方的取值范围为[0, c^2],那么a、b的取值范围为[0, floor(sqrt(c))],floor表示向下取整。
那么我们假设a为较小的非负整数,b为较大的非负整数,a的初始值为0,b的初始值为floor(sqrt(c)),计算a*a+b*b看看是否等于c,如果等于直接返回true,如果小于则a++,如果大于则b--。也就是让a和b不断靠拢(双指针法),当a>b并且仍然没有满足条件的两个整数时,则返回false。
时间复杂度为O(sqrt(c))
二、代码实现
class Solution {
public boolean judgeSquareSum(int c) {
if (c < 0) {
return false;
}
//c >= 0
int a = 0, b = (int)Math.sqrt(c);
while (a <= b) {
int sum = a*a + b*b;
if (sum == c) {
return true;
} else if (sum < c) {
a++;
} else {
// sum > c
b--;
}
}
return false;
}
}
其他值得参考的方法:
https://leetcode.com/problems/sum-of-square-numbers/discuss/104935/Fermat
https://leetcode.com/problems/sum-of-square-numbers/discuss/104938/Simple-C%2B%2B-Solution
https://leetcode.com/problems/sum-of-square-numbers/discuss/104940/Java-3-Liner