本文主要是介绍leetcode【633】Sum of Square Numbers,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
写在最前面:
一道easy题,如何控制时间复杂度是重点。
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(object):def judgeSquareSum(self, c):""":type c: int:rtype: bool"""if c == 1 | c == 0:return Truefor i in range(c):for j in range(c):if i**2 + j**2 ==c:return Truereturn False
然后我们再多想一点:
class Solution:def judgeSquareSum(self, c):""":type c: int:rtype: bool"""if int(c**0.5) == c**0.5:return Trueelse:high = int(c**0.5)low = 1while low <= high:if low**2 + high**2 > c:high -= 1elif low**2 + high**2 < c:low += 1else:return Truereturn False
这篇关于leetcode【633】Sum of Square Numbers的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!