给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c。
示例 1:
输入: 5
输出: True
解释: 1 * 1 + 2 * 2 = 5
示例 2:
输入: 3
输出: False
bool judgeSquareSum(int c) {
long i = 0, j = (int) sqrt(c), tmp;
while (i <= j) {
tmp = i * i + j * j - c;
if (tmp == 0) return true;
if (tmp > 0) j = j - 1;
else i = i + 1;
}
return false;
}
解释: 令a = 0,b = 根号c + 1,在a <= b 前提下,如果a方+b方小于c,则将a++,大于则将b++,等于直接返回true,当不满足a <= b时,则说明没有满足的组合,返回false。
知识点回顾: 双指针技巧的使用。
class Solution {
public boolean judgeSquareSum(int c) {
//StrictMath.sqrt() 开平方
//StrictMath.pow(left,2)速度还不如left*left
int left = 0, right = (int) StrictMath.sqrt(c);
while (left <= right) {
int sum = left * left + right * right;
if (sum < c) left++;
else if (sum > c) right--;
else return true;
}
return false;
}
}
解释: 类似于C语言的求解思路。
知识点回顾: 双指针技巧的使用。
class Solution:
def judgeSquareSum(self, c: int) -> bool:
j=int(math.sqrt(c))
i=0
while i <=j:
if c==i*i+j*j:
return True
elif i*i+j*j>c:
j=j-1
else:
i=i+1
解释: 类似于C语言的求解思路。
知识点回顾: 双指针技巧的使用。
/**
* @param {number} c
* @return {boolean}
*/
var judgeSquareSum = function(c) {
const flag = Math.sqrt(0.5) * Math.sqrt(c)
for(let a = 0;a <= flag; a++){
const b = Math.sqrt(c - a*a)
if(parseInt(b) === b){
return true
}
}
return false
};
解释:
知识点回顾: 无。
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- igat.cn 版权所有 赣ICP备2024042791号-1
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务