LeetCode刷题记录——第633题(平方数之和)

版权声明:此BLOG为个人BLOG,内容均来自原创及互连网转载。最终目的为记录自己需要的内容或自己的学习感悟,不涉及商业用途,转载请附上原博客。 https://blog.csdn.net/bulo1025/article/details/87774513

题目描述

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

示例1:

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

示例2:

输入: 3
输出: False

思路分析

  • 如果输入的 c 能够直接分解为一个整数的平方,返回 True
  • 如果不行,很正常的想法就是用到二分法来找到需要的数,如果两个数平方的和大于 c,将high 更新;如果两个数平方和小于 c,将 low 更新;如果两个数平方和等于 c,返回 True
  • 如果都不满足,直接返回 False

代码示例

class Solution(object):
    def judgeSquareSum(self, c):
        """
        :type c: int
        :rtype: bool
        """
        if int(c ** 0.5) == c ** 0.5:
            return True
        else:
            high = int(c ** 0.5)
        low = 1
        while low <= high:
            if low ** 2 + high ** 2 > c:
                high -= 1
            elif low ** 2 + high ** 2 < c:
                low += 1
            else:
                return True
        return False

猜你喜欢

转载自blog.csdn.net/bulo1025/article/details/87774513