题目描述:
思路:枚举法or双指针
因为我们要得到两个数的平方和等于目标数,也就是说a和b的大小范围是在0到根号c之间的。(c为目标数)
这里主要说一下为什么双指针可行,(设置两个指针,判断两个指针的平方和与目标数的大小,若大于,则右指针--,小于则左指针++)(右指针一开始赋值为(int)根号c)
代码如下:
class Solution {
public boolean judgeSquareSum(int c) {
/*
//a,c都属于(0,根号c]
//枚举A
long i=(int)Math.sqrt(c);
for(int a=0;a<=i;a++){
double b=Math.sqrt(c-a*a);
if(b==(int)b){
return true;
}
}
return false;*/
//双指针解法
int left=0,right=(int)Math.sqrt(c);
while (left<=right){
if(left*left+right*right==c) return true;
else if(left*left+right*right<c){
left++;
}
else right--;
}
return false;
}
}