LeetCode 0633.平方数之和:模拟

【LetMeFly】633.平方数之和:模拟

力扣题目链接:https://leetcode.cn/problems/sum-of-square-numbers/

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

 

示例 1:

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

示例 2:

输入:c = 3
输出:false

 

提示:

  • 0 <= c <= 231 - 1

解题方法:模拟

0 0 0 c \sqrt{c} c 模拟 a a a,令 b = i n t ( c − a 2 ) b=int(\sqrt{c-a^2}) b=int(ca2 )。如果 a 2 + b 2 = c a^2+b^2=c a2+b2=c则返回true

  • 时间复杂度 O ( c ) O(\sqrt{c}) O(c )
  • 空间复杂度 O ( 1 ) O(1) O(1)

AC代码

C++
class Solution {
public:
    bool judgeSquareSum(int c) {
        for (int a = sqrt(c); a >= 0; a--) {
            int b = sqrt(c - a * a);
            if (b * b + a * a == c) {
                return true;
            }
        }
        return false;
    }
};
Python
from math import sqrt

class Solution:
    def judgeSquareSum(self, c: int) -> bool:
        for a in range(int(sqrt(c)) + 1):
            b = sqrt(c - a * a)
            if b == int(b):
                return True
        return False
Java
class Solution {
    public boolean judgeSquareSum(int c) {
        for (int a = (int)Math.sqrt(c); a >= 0; a--) {
            int b = (int)Math.sqrt(c - a * a);
            if (a * a + b * b == c) {
                return true;
            }
        }
        return false;
    }
}
Go
package main
import "math"

func judgeSquareSum(c int) bool {
    for a := int(math.Sqrt(float64(c))); a >= 0; a-- {
        b := int(math.Sqrt(float64(c - a * a)))
        if a * a + b * b == c {
            return true
        }
    }
    return false
}

同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~

Tisfy:https://letmefly.blog.csdn.net/article/details/143495591

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Tisfy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值