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

这道题让我们求一个数是否能由平方数之和组成,刚开始博主没仔细看题,没有看到必须要是两个平方数之和,博主以为任意一个就可以。所以写了个带优化的递归解法,博主已经不是上来就无脑暴力破解的辣个青葱骚年了,直接带优化。可是居然对 14 返回 false,难道 14 不等于 1+4+9 吗,结果仔细一看,必须要两个平方数之和。好吧,那么递归都省了,直接判断两次就行了。我们可以从c的平方根,注意即使c不是平方数,也会返回一个整型数。然后我们判断如果 i*i 等于c,说明c就是个平方数,只要再凑个0,就是两个平方数之和,返回 true;如果不等于的话,那么算出差值 c - i*i,如果这个差值也是平方数的话,返回 true。遍历结束后返回 false,参见代码如下:

解法一:

class Solution {
public:
bool judgeSquareSum(int c) {
for (int i = sqrt(c); i >= ; --i) {
if (i * i == c) return true;
int d = c - i * i, t = sqrt(d);
if (t * t == d) return true;
}
return false;
}
};

下面这种方法用到了 HashSet,从0遍历到c的平方根,对于每个i*i,都加入 HashSet 中,然后计算 c - i*i,如果这个差值也在 HashSet 中,返回 true,遍历结束返回 false,参见代码如下:

解法二:

class Solution {
public:
bool judgeSquareSum(int c) {
unordered_set<int> s;
for (int i = ; i <= sqrt(c); ++i) {
s.insert(i * i);
if (s.count(c - i * i)) return true;
}
return false;
}
};

上面两种方法都不是很高效,来看下面这种高效的解法。论坛上有人称之为二分解法,但是博主怎么觉得不是呢,虽然样子很像,但是并没有折半的操作啊。这里用a和b代表了左右两个范围,分别为0和c的平方根,然后 while 循环遍历,如果 a*a + b*b 刚好等于c,那么返回 true;如果小于c,则a增大1;反之如果大于c,则b自减1,参见代码如下:

解法三:

class Solution {
public:
bool judgeSquareSum(int c) {
long a = , b = sqrt(c);
while (a <= b) {
if (a * a + b * b == c) return true;
else if (a * a + b * b < c) ++a;
else --b;
}
return false;
}
};

下面这种解法基于费马平方和定理 Fermat's theorem on sums of two squares 的一般推广形式:当某个数字的 4k+3 型的质数因子的个数均为偶数时,其可以拆分为两个平方数之和(each prime that is congruent to 3 mod 4 appears with an even exponent in the prime factorization of the number)。那么我们只要统计其质数因子的个数,并且判读,若其为 4k+3 型且出现次数为奇数的话直接返回 false。这里,我们从2开始遍历,若能整除2,则计数器加1,并且c也要除以2。这样我们找到都会是质数因子,因为非质数因子中的因子已经在之前被除掉了,这也是个 trick,需要自己好好想一下。最终在循环退出后,我们还要再判断一下,若剩余的质数因子还是个 4k+3 型,那么返回 false,否则返回 true,参见代码如下:

解法四:

class Solution {
public:
bool judgeSquareSum(int c) {
for (int i = ; i * i <= c; ++i) {
if (c % i != ) continue;
int cnt = ;
while (c % i == ) {
++cnt;
c /= i;
}
if (i % == && cnt % != ) return false;
}
return c % != ;
}
};

类似题目:

Valid Perfect Square

参考资料:

https://leetcode.com/problems/sum-of-square-numbers/

https://leetcode.com/problems/sum-of-square-numbers/discuss/104938/simple-c-solution

https://leetcode.com/problems/sum-of-square-numbers/discuss/104930/java-two-pointers-solution

https://leetcode.com/problems/sum-of-square-numbers/discuss/104932/hashset-java-quick-solution-one-for-loop

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 633. Sum of Square Numbers 平方数之和的更多相关文章

  1. LeetCode 633. Sum of Square Numbers平方数之和 (C++)

    题目: Given a non-negative integer c, your task is to decide whether there're two integers a and b suc ...

  2. [LeetCode] Sum of Square Numbers 平方数之和

    Given a non-negative integer c, your task is to decide whether there're two integers a and b such th ...

  3. Leetcode633.Sum of Square Numbers平方数之和

    给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c. 示例1: 输入: 5 输出: True 解释: 1 * 1 + 2 * 2 = 5 示例2: 输入: 3 ...

  4. #Leetcode# 633. Sum of Square Numbers

    https://leetcode.com/problems/sum-of-square-numbers/ Given a non-negative integer c, your task is to ...

  5. 【Leetcode_easy】633. Sum of Square Numbers

    problem 633. Sum of Square Numbers 题意: solution1: 可以从c的平方根,注意即使c不是平方数,也会返回一个整型数.然后我们判断如果 i*i 等于c,说明c ...

  6. 【LeetCode】633. Sum of Square Numbers 解题报告(python & Java & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双指针 列表生成式 循环 日期 题目地址:https ...

  7. 【leetcode】633. Sum of Square Numbers(two-sum 变形)

    Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c. ...

  8. 【LeetCode】633. Sum of Square Numbers

    Difficulty: Easy  More:[目录]LeetCode Java实现 Description https://leetcode.com/problems/sum-of-square-n ...

  9. 633. Sum of Square Numbers【Easy】【双指针-是否存在两个数的平方和等于给定目标值】

    Given a non-negative integer c, your task is to decide whether there're two integers a and bsuch tha ...

随机推荐

  1. flink 注册函数示例

    需求 (filter): 现在有这么一个需求,统计出现在纽约的行车记录.这里我们需要进行一个过滤的操作,我们需要有个自定义的 UDF ,具体思路是,表里面有经度和维度这两个字段,通过这个可以来开发一个 ...

  2. pixijs shader 扫光加强版

    pixijs shader 扫光加强版 const app = new PIXI.Application({ transparent: true }); document.body.appendChi ...

  3. 微信小程序开发语音识别文字教程

    微信小程序开发语音识别文字教程 现在后台 添加插件 微信同声传译 然后app.json 加入插件 "plugins": { "WechatSI": { &quo ...

  4. python asyncio 协程调用task步骤

    import asyncio async def compute(x, y): print("Compute %s + %s ..." % (x, y)) await asynci ...

  5. 最锋利的Visual Studio Web开发工具扩展:Web Essentials详解【转】

    Web Essentials是目前为止见过的最好用的VS扩展工具了,具体功能请待我一一道来. 首先,从Extension Manager里安装:最新版本是19号发布的2.5版 然后重启你的VS开发环境 ...

  6. IDEA 日常小技巧

    原文首发于 studyidea.cn点击查看更多技巧 适用于 IDEA 2019.2 之前版本 ,2019.2 版本以下功能默认开启. Surround a selection with a quot ...

  7. Linux学习笔记之scp远程拷贝文件

    0x00 拷贝本机/home/administrator/test整个目录至远程主机192.168.1.100的/root目录下 代码如下: scp -r /home/administrator/te ...

  8. C# 流介绍 (原发布 csdn 2017-09-15 23:37:52)

    1.FileStream FileStream 详细介绍参考msdn 写数据: using (FileStream fs = new FileStream("File.FileStream& ...

  9. VMware 虚拟机网络配置

    随手记: 近期需要安装几个服务器,编写负载均衡NLB的教程,使用到虚拟机: VMware-workstation-full-15.0.2-10952284.exe cn_windows_server_ ...

  10. SAP MM MIGO过账报错 - 用本币计算的余额 - 之对策

    SAP MM MIGO过账报错 - 用本币计算的余额 - 之对策 使用MIGO事务代码对采购订单4500000191,执行收货,系统报错: 详细错误信息如下: 用本币计算的余额 消息号 F5703 诊 ...