633. 平方數之和
給定一個非負整數 c ,你要判斷是否存在兩個整數 a 和 b,使得 a2 + b2 = c。
示例1:
輸入:
5
輸出:
True
解釋: 1 * 1 + 2 * 2 = 5
示例2:
輸入:
3
輸出:
False
思路:
用雙指針 , l , r 分別是左,右指針,由題意得 a 和 b 不可能大於或等於 c 的平方根, 故右指針從 c 的平方根開始
代碼:
class Solution {
public:
bool judgeSquareSum(int c) {
long long int l=0, r=(int)sqrt(c);
while(l<=r)
{
if(l*l+r*r==c)return true;
if(l*l+r*r<c)l++;
else r--;
}
return false;
}
};
雙百得曬一曬