「这是我参与11月更文挑战的第5天,活动详情查看:2021最后一次更文挑战」
LeetCode633.平放数之和,两种解法(枚举+双指针)
题目要求
给定一个非负整数
c,你要判断是否存在两个整数a和b,使得a2 + b2 = c。
示例
输入:c = 5
输出:true
解释:1 * 1 + 2 * 2 = 5
思路1(枚举)
1.因为这里是a^2 + b^2 = c,所以我们要先求出来a或b的最大值
let max = Math.floor(Math.sqrt(c));
2.让a小于等于max,求出来b的值,然后判断a^2 + b^2 是否等于 c
for (let a = 0; a <= max; a++) {
let b = Math.floor(Math.sqrt(c - a * a));
if (a * a + b * b = c) return true;
}
return false;
完整代码
var judgeSquareSum = function(c) {
let max = Math.floor(Math.sqrt(c));
for (let a = 0; a <= max; a++) {
let b = Math.floor(Math.sqrt(c - a * a));
if (a * a + b * b == c) return true;
}
return false;
};
思路2(双指针)
1. 声明两个值一个最大值,一个最小值
let small = 0;
let big = Math.floor(Math.sqrt(c));
2.判断当small小于等于big的时候
-
如果small^2 + big^2 = c,说明存在这个数return true
-
如果small^2 + big^2 > c, big做自减操作
-
如果small^2 + big^2 < c, small做自增操作
while (small <= big) {
let sum = small * small + big * big;
if (sum == c) {
return true;
} else if (sum > c) {
big--;
} else {
small++;
} } return false;
完整代码
var judgeSquareSum = function(c) {
let small = 0;
let big = Math.floor(Math.sqrt(c));
while (small <= big) {
let sum = small * small + big * big;
if (sum == c) {
return true;
} else if (sum > c) {
big--;
} else {
small++;
}
}
return false;
}