题目描述
给定一个非负整数 c
,你要判断是否存在两个整数 a
和 b
,使得 a2 + b2 = c
。
解题思路
- 本题还是采用双指针法遍历;
- 建立两个指针变量first和last,其中first从0开始,last从c开始,但是可以节省搜索范围直接从sqrt(c)开始搜索,因为除了1,一个数的平方不可能是他本身;
- 将c开方后的last记得转为int;
- 接下来遍历,如果res和c相等,那么则为true;
- 如果res<c,则first++;
- 反之,last--;
- 最终找到正确答案;
在提交过程中,出现错误,由于 0 <= c <= 231 - 1,但是res会超出范围,所以应该将first、last、res变量定义为long型,为了节约内存耗费,也可以把first或last其中之一定义为long就行。
输入输出示例
代码
class Solution {
public boolean judgeSquareSum(int c) {
if(c<0) return false;//没有一个数的平方为负数
int first = 0;//定义左指针
long last = (int)Math.sqrt(c);//剪枝,就是排除一部分不可能的值
while(first <= last){
long res = first * first + last * last;//定义两数的平方和
if(res == c){
return true;
}else if(res < c){
first++;
}else{
last--;
}
}
return false;
}
}