方法一:双指针
思路类似LeetCode 167 两数之和II
不同的时,这里对j进行了剪枝,j初始化为 (int)Math.sqrt©;
class Solution {
public boolean judgeSquareSum(int c) {
if(c<0) return false;
int i = 0, j = (int)Math.sqrt(c);
while(i<=j){
int sum = i*i + j*j;
if(sum == c) return true;
else if(sum>c) j--;
else i++;
}
return false;
}
}
方法二:(官方题解)
不明白为什么有些变量要改为 long;
class Solution {
public boolean judgeSquareSum(int c) {
//if(c<0) return false;
for(long i = 0;i*i<=c;i++){
int end = c - (int)(i*i);
if(binarySearch(0,end,end)) return true;
}
return false;
}
public boolean binarySearch(long start, long end , int target){
if(start>end) return false;
//int mid = (start + end) /2;
long mid = start +(end - start)/2;
if(mid * mid ==target) return true;
if(mid * mid >target)
return binarySearch(start,mid-1,target);
return binarySearch(mid+1,end,target);
}
}
方法三:
数学方法
public class Solution {
public boolean judgeSquareSum(int c) {
for (int i = 2; i * i <= c; i++) {
int count = 0;
if (c % i == 0) {
while (c % i == 0) {
count++;
c /= i;
}
if (i % 4 == 3 && count % 2 != 0)
return false;
}
}
return c % 4 != 3;
}
}