题目:
给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a^2 + b^2 = c。
示例:
image.png
思路:
双指针
一个指针指向可取的最小数;一个指针指向可取的最大数;
如果两个数的平方和等于给出的非负整数,则返回真,否则返回假;
如果两个数的平方和大于给出的非负整数,则指向可取最大数的指针减一;
如果两个数的平方和小于给出的非负整数,则指向可取最小数的指针加一;
代码:
class Solution {
public boolean judgeSquareSum(int c) {
int index1 = 0;
int index2 = (int) Math.sqrt(c);//可取的最大数
while (index1 <= index2) {
int sum = index1 * index1 + index2 * index2;
if (sum == c) return true;
if (sum > c) {
index2 --;
}else if (sum < c) {
index1 ++;
}
}
return false;
}
}
时间复杂度:O(n),空间复杂度:O(1)