LeetCode633-平方数之和

题目链接

英文链接:https://leetcode.com/problems/sum-of-square-numbers/

中文链接:https://leetcode-cn.com/problems/sum-of-square-numbers/

题目详述

给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a^2 + b^2 = c。

示例1:

1
2
3
输入: 5
输出: True
解释: 1 * 1 + 2 * 2 = 5

示例2:

1
2
输入: 3
输出: False

题目详解

运用双指针扫描。从两端往中间扫描,左端点起始值为 0,右端点起始值为 c 的平方根。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class LeetCode_00633 {

public boolean judgeSquareSum(int c) {
int i = 0, j = (int) Math.sqrt(c);
while (i <= j) {
int s = i * i + j * j;
if (s < c) {
++i;
} else if (s > c) {
--j;
} else {
return true;
}
}
return false;
}
}