633. Sum of Square Numbers
Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c.
Example 1:
Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3
Output: False
解法
两根指针
class Solution:
def judgeSquareSum(self, c: int) -> bool:
start = 0
end = int(c ** 0.5) # must convert to integer
while start <= end: # for test 0, 1, 2
sum = start ** 2 + end ** 2 # time consuming, do not judge it in if
if sum == c:
return True
elif sum > c:
end -= 1
else:
start += 1
return False
使用集合
class Solution:
def judgeSquareSum(self, c: int) -> bool:
hash_table = set()
for i in range(0, int(c ** 0.5) + 1):
hash_table.add(i ** 2)
for each in hash_table:
if c - each in hash_table:
return True
return False
Last updated
Was this helpful?