633.平方数之和
题目
给定一个非负整数c,要判断是否存在两个整数a和b,使得
a
2
+
b
2
=
c
a^2+b^2=c
a2+b2=c
示例:
输入:c=5
输出:true
解释:1*1+2*2=5
思路
一开始我的想法是设置两个指针,范围是从0到c,然后开始遍历寻找,后来通过测试崩了,我再细细想了一下,发现,应该从最极端的结果开始入手,假设c=5,那么a=0的时候,b就只能是 b \sqrt b b,由此可以得出,末位指针应该指向根号c。这样确定上界方式应该会比较有依据
代码
class Solution:
def judgeSquareSum(self, c: int) -> bool:
if c<0:
return False
start,end=0,int(sqrt(c))
while start<=end:
result=start**2+end**2
if result<c:
start+=1
elif result>c:
end-=1
else:
return True
return False
测试用例
import math
def judgeSquareSum(c):
if c<0:
return False #此处的另一种写法是assert c>=0
start,end=0,int(math.sqrt(c))
while start<=end:
result=start*start+end*end
if result<c:
start+=1
elif result>c:
end-=1
else:
return True
return False
print(judgeSquareSum(4))
注意:这里的 start 和 end是需要考虑相等的情况,因为有可能出现 2^2+ 2^2=8