上篇文章中一道数学问题 - 自除数,今天我们接着分析 LeetCode 中的另一道数学题吧~

系列教程索引

传送门:https://enjoy233.cnblogs.com/articles/leetcode_csharp_index.html

  1. C#刷遍Leetcode面试题系列连载(1) - 入门与工具简介
  2. C#刷遍Leetcode面试题系列连载(2): No.38 - 报数
  3. C# 刷遍 Leetcode 面试题系列连载(3): No.728 - 自除数
  4. C#刷遍Leetcode面试题系列连载(4):No.633 - 平方数之和

今天要给大家分析的面试题是 LeetCode 上第 633 号问题,

Leetcode 633 - 平方数之和

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

题目描述

给定一个非负整数 c ,你要判断是否存在两个整数 a和 b,使得 \(a^2 + b^2 = c\)。

示例1:

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

示例2:

输入: 3
输出: False

Input:

5
2
100

Expected answer:

true
true
true

相关话题

相似题目


解题思路:

做一次循环,用目标和减去循环变量的平方,如果剩下的部分依然是完全平方的情形存在,就返回true;否则返回false。

假定 $i \leq a \leq b $,根据数据的对称性,循环变量 i 只需取到 $i^2 \cdot 2 \leq c $ 即可覆盖所有情形.

已AC代码:

最初版本:

public class Solution
{
public bool JudgeSquareSum(int c)
{
for (int i = 0; c - 2 * i * i >= 0; i++)
{
double diff = c - i*i;
if ((int)(Math.Ceiling(Math.Sqrt(diff))) == (int)(Math.Floor(Math.Sqrt(diff)))) // 若向上取整=向下取整,则该数开方后是整数
return true;
} return false;
}
}

Rank:

执行用时: 56 ms, 在所有 csharp 提交中击败了68.18%的用户.

优化1:

public class Solution
{
public bool JudgeSquareSum(int c)
{
for (int i = 0; c - 2 * i * i >= 0; i++)
{
int diff = c - i*i;
if (IsPerfectSquare(diff))
return true;
} return false;
}
private bool IsPerfectSquare(int num)
{
double sq1 = Math.Sqrt(num);
int sq2 = (int)Math.Sqrt(num);
if (Math.Abs(sq1 - (double)sq2) < 10e-10)
return true;
return false;
}
}

Rank:

执行用时: 52 ms, 在所有 csharp 提交中击败了90.91%的用户.

优化2(根据文末参考资料[1]中MPUCoder 的回答改写):

public class Solution
{
public bool JudgeSquareSum(int c)
{
for (int i = 0; i <= c && c - i * i >= 0; i++)
{
int diff = c - i*i;
if (IsPerfectSquare(diff))
return true;
} return false;
}
public bool IsPerfectSquare(int num)
{
if ((0x0213 & (1 << (num & 15))) != 0) //TRUE only if n mod 16 is 0, 1, 4, or 9
{
int t = (int)Math.Floor(Math.Sqrt((double)num) + 0.5);
return t * t == num;
}
return false;
}
}

Rank:

执行用时: 44 ms, 在所有 csharp 提交中击败了100.00%的用户.

优化3(根据文末参考资料[1]中 Simon 的回答改写):

public class Solution
{
public bool JudgeSquareSum(int c)
{
for (int i = 0; c - i * i >= 0; i++)
{
long diff = c - i*i;
if (IsSquareFast(diff))
return true;
} return false;
} bool IsSquareFast(long n)
{
if ((0x2030213 & (1 << (int)(n & 31))) > 0)
{
long t = (long)Math.Round(Math.Sqrt((double)n));
bool result = t * t == n;
return result;
}
return false;
}
}

Rank:

执行用时: 48 ms, 在所有 csharp 提交中击败了100.00%的用户.

另外,stackoverflow上还推荐了一种写法:

public class Solution
{
public bool JudgeSquareSum(int c)
{
for (int i = 0; c - 2 * i * i >= 0; i++)
{
double diff = c - i*i;
if (Math.Abs(Math.Sqrt(diff) % 1) < 0.000001)
return true;
} return false;
}
}

事实上,速度并不快~

Rank:

执行用时: 68 ms, 在所有 csharp 提交中击败了27.27%的用户.

双"指针" 解法:

左指针 l=0,右指针 r = √C,夹逼条件是 $ l^2 + r^2 = C $

时间复杂度 log(n), 感谢 @msp的昌伟哥哥 的补充和指正~

    public class Solution
{
public bool JudgeSquareSum(int c)
{
var r = (int)Math.Sqrt(c);
var l = 0;
while (l <= r)
{
var sum = l * l + r * r;
if (sum == c)
return true; if (sum < c)
l++;
else
r--;
} return false;
} // 以下为测试
public static void Main(string[] args)
{
var sol = new Solution();
var res = sol.JudgeSquareSum(25);
Console.WriteLine(res);
}
}

Rank:

执行用时: 40 ms, 在所有 csharp 提交中击败了 100.00% 的用户.

相应代码已经上传到github:

https://github.com/yanglr/Leetcode-CSharp/tree/master/leetcode633

参考资料:

[1] Fast way to test whether a number is a square

https://www.johndcook.com/blog/2008/11/17/fast-way-to-test-whether-a-number-is-a-square/

[2] Shortest way to check perfect Square? - C#

https://stackoverflow.com/questions/4885925/shortest-way-to-check-perfect-square/4886006#4886006


作者简介:Bravo Yeung,计算机硕士,知乎干货答主(获81K 赞同, 38K 感谢, 235K 收藏)。曾在国内 Top3互联网视频直播公司工作过,后加入一家外企做软件开发至今。

如需转载,请加微信 iMath7 申请开白!

欢迎在留言区留下你的观点,一起讨论提高。如果今天的文章让你有新的启发,学习能力的提升上有新的认识,欢迎转发分享给更多人。

欢迎各位读者加入 .NET技术交流群,在公众号后台回复“加群”或者“学习”即可。

文末彩蛋

微信后台回复“asp”,给你:一份全网最强的ASP.NET学习路线图。



回复“cs”,给你:一整套 C# 和 WPF 学习资源!



回复“core”,给你:2019年dotConf大会上发布的.NET core 3.0学习视频!

C#刷遍Leetcode面试题系列连载(4) No.633 - 平方数之和的更多相关文章

  1. C#刷遍Leetcode面试题系列连载(1) - 入门与工具简介

    目录 为什么要刷LeetCode 刷LeetCode有哪些好处? LeetCode vs 传统的 OJ LeetCode刷题时的心态建设 C#如何刷遍LeetCode 选项1: VS本地Debug + ...

  2. C#刷遍Leetcode面试题系列连载(2): No.38 - 报数

    目录 前言 题目描述 相关话题 相似题目 解题思路: 运行结果: 代码要点: 参考资料: 文末彩蛋 前言 前文传送门: C# 刷遍 Leetcode 面试题系列连载(1) - 入门与工具简介 上篇文章 ...

  3. C#刷遍Leetcode面试题系列连载(5):No.593 - 有效的正方形

    上一篇 LeetCode 面试题中,我们分析了一道难度为 Easy 的数学题 - 自除数,提供了两种方法.今天我们来分析一道难度为 Medium 的面试题. 今天要给大家分析的面试题是 LeetCod ...

  4. C# 刷遍 Leetcode 面试题系列连载(3): No.728 - 自除数

    前文传送门: C#刷遍Leetcode面试题系列连载(1) - 入门与工具简介 C#刷遍Leetcode面试题系列连载(2): No.38 - 报数 系列教程索引 传送门:https://enjoy2 ...

  5. C#版 - Leetcode 633. 平方数之和 - 题解

    版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址 http://blog.csdn.net/lzuacm. C#版 - L ...

  6. LeetCode 633. 平方数之和

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

  7. leetcode.双指针.633平方数之和-Java

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

  8. Java实现 LeetCode 633 平方数之和(暴力大法)

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

  9. C#刷遍Leetcode系列连载 索引

    C#刷遍Leetcode系列文章 索引 索引(陆续发布中,请保持关注) C#刷遍Leetcode面试题系列连载(1) - 入门与工具简介 C#刷遍Leetcode面试题系列连载(2): No.38 - ...

随机推荐

  1. cython的安装

    cython 在linux(ubuntu)下安装 sudo apt-get install cython 安装后  输入 cython 即可验证是否安装成功

  2. 【Python爬虫】第四课(查询照片拍摄地址)

    首先,要能够查询到照片地址,查询的照片必须要开GPS拍,且上传时用原图…… 查询图片的exif信息,使用exifread包 import exifread img = exifread.process ...

  3. Android手机QQ文件夹解析

    注:切勿修改手机QQ文件夹,以免造成不必要的使用问题及无法修复的数据丢失] 安卓手机QQ tencent文件夹解析 QQ下载的聊天背景:tencent→MobileQQ→system_backgrou ...

  4. 删除linux自带jdk

    提示:error: can't create transaction lock on /var/lib/rpm/.rpm.lock (Permission denied):代表权限不够 执行:su r ...

  5. C++ 变量判定的螺旋法则

    C++ 中一个标识符配合着各种修饰界定符,使得标识符的本意不那么直观一眼就能看出,甚至需要仔细分析,才能知道该标识符的具体你含义. 比如: void (*signal(int, void (*fp)( ...

  6. dom4j.jar下载

    下载地址: 链接:https://pan.baidu.com/s/16GCgCpaF7dc33pMbK2sTLg 密码:z444

  7. layui select获取自定义属性值

    layui-select写法: <option value='> 我想在点击的时候获取自定义属性data-method的值,其中selectId是该select的id form.on('s ...

  8. thymeleaf常用配置说明

    #spring.thymeleaf.cache = true #启用模板缓存. #spring.thymeleaf.check-template = true #在呈现模板之前检查模板是否存在. #s ...

  9. KD-tree学习笔记(超全!)

    目录 K-D树 更新信息 建树 插入 查询 k远/近询问 重构 K-D 树优化建边 后记 因为之前找不到全的博客,唯一的一篇码风比较毒瘤... 所以我就来写了 K-D树 大概是高维二叉树吧 每次按一个 ...

  10. 怎样实现给DEDE5.7的栏目增加栏目图片

    前两天用DEDE做二次开发的时候,遇到一个问题,领导让给每个栏目增加一个栏目图片的功能,网上找了些东西,结合自己实际做的时候的方法,下面详细描述下具体的实现方式(只测试了V5.7版本,对低版本是否适用 ...