0
点赞
收藏
分享

微信扫一扫

力扣每日一题:633.平方数之和

小沙坨 2021-09-26 阅读 58
Python当歌

633.平方数之和

题目:

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

提示:

0 <= c <= 231 - 1

示例:

示例 1:

输入:c = 5
输出:true
解释:1 * 1 + 2 * 2 = 5
示例 2:

输入:c = 3
输出:false
示例 3:

输入:c = 4
输出:true
示例 4:

输入:c = 2
输出:true
示例 5:

输入:c = 1
输出:true

分析

这道题感觉有些不符合中等题的难度,题目有些短所以理解上有些出入。

描述C的时候专门说是非负整数,说a和b的时候又成了整数,但其实a b均可以为0。

提供for循环调用sqrt 和 双指针两种解题,但本质上差别不大。

解题:

from math import sqrt

class Solution:
    def judgeSquareSum(self, c: int) -> bool:
        r = int(sqrt(c))
        for num in range(r + 1):
            if sqrt(c - num ** 2) % 1 == 0:
                return True
        return False
class Solution:
    def judgeSquareSum(self, c):
        left = 0
        right = int(c ** 0.5) + 1
        while left <= right:
            total = left ** 2 + right ** 2
            if total == c:
                return True
            elif total > c:
                right -= 1
            else:
                left += 1
        return False

我的个人博客:https://qingfengpython.cn

力扣解题合集:https://github.com/BreezePython/AlgorithmMarkdown

举报

相关推荐

0 条评论