本题目给到我们一个正整数 c,要求我们找出是否有正整数 a,b 符合等式:a^2 + b^2 = c
一个简单的想法就是用两个指针 a,b 往中间夹紧遍历,如果直到 a>b 还没找到,那么就可以返回 false 了
- a 一般从 0 开始(因为不能排除有
b^2 = c
的可能性) - b 则从
sqrt(c)
开始(因为 b 最大的情况就刚好是 c 开根号)
/**
* @param {number} c
* @return {boolean}
*/
var judgeSquareSum = function(c) {
let a = 0;
let b = Math.floor(Math.sqrt(c));
while(a <= b) {
let res = a*a + b*b
if(res === c) {
return true;
} else if(res < c) {
a++;
} else {
b--;
}
}
return false;
};