[leetcode]Python实现-633.平方数之和

633.平方数之和

描述

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

示例

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

思路:使用双指针法,最小为0,最大为输入数的平方根,判断当前两个指针是否满足要求,然后相应移动l或者h

class Solution:
    def judgeSquareSum(self, c):
        """
        :type c: int
        :rtype: bool
        """
        l = 0
        h = int(c**0.5)
        while l <= h:
            tmp = l ** 2 + h ** 2
            if tmp < c:
                l+=1
            elif tmp == c:
                return True
            else:
                h -= 1
        return False

猜你喜欢

转载自blog.csdn.net/qq_34364995/article/details/80725887