LeetCode/633. 平方数之和

633. 平方数之和

给定一个非负整数 c ,你要判断是否存在两个整数 ab,使得 a2 + b2 = c

示例1 :

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

示例2:

1
2
输入: 3
输出: False

来源:力扣(LeetCode)
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解:

本题基于双指针法,创建两个指针,一个指向头,一个指向尾,但在数学中我们知道,两数只需要判断到小于目标数字c的开方即可。

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public boolean judgeSquareSum(int c) {
int left = 0, right = (int) Math.sqrt(c);
while (left <= right) {
if (left * left + right * right == c)
return true;
else if (left * left + right * right > c)
right--;
else
left++;
}
return false;
}
}

Comments