LeetCode 题解工作台
平方数之和
给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b ,使得 a 2 + b 2 = c 。 示例 1: 输入: c = 5 输出: true 解释: 1 * 1 + 2 * 2 = 5 示例 2: 输入: c = 3 输出: false 提示: 0 31 - 1
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 二分·搜索·答案·空间
答案摘要
我们可以使用双指针的方法来解决这个问题,定义两个指针 和 ,分别指向 和 。在每一步中,我们会计算 $s = a^2 + b^2$ 的值,然后比较 与 的大小。如果 $s = c$,我们就找到了两个整数 和 ,使得 $a^2 + b^2 = c$。如果 $s < c$,我们将 的值增加 ,如果 $s > c$,我们将 的值减小 。我们不断进行这个过程直到找到答案,或者 的值大于 …
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c 。
示例 1:
输入:c = 5 输出:true 解释:1 * 1 + 2 * 2 = 5
示例 2:
输入:c = 3 输出:false
提示:
0 <= c <= 231 - 1
解题思路
方法一:数学 + 双指针
我们可以使用双指针的方法来解决这个问题,定义两个指针 和 ,分别指向 和 。在每一步中,我们会计算 的值,然后比较 与 的大小。如果 ,我们就找到了两个整数 和 ,使得 。如果 ,我们将 的值增加 ,如果 ,我们将 的值减小 。我们不断进行这个过程直到找到答案,或者 的值大于 的值,返回 false。
时间复杂度 ,其中 是给定的非负整数。空间复杂度 。
class Solution:
def judgeSquareSum(self, c: int) -> bool:
a, b = 0, int(sqrt(c))
while a <= b:
s = a**2 + b**2
if s == c:
return True
if s < c:
a += 1
else:
b -= 1
return False
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Tests the candidate's ability to apply binary search over a valid range efficiently.
- question_mark
Assesses understanding of two-pointer techniques in algorithmic problem-solving.
- question_mark
Evaluates the candidate's ability to recognize patterns in math-based problems.
常见陷阱
外企场景- error
Failing to optimize the search space, leading to unnecessarily complex solutions.
- error
Overcomplicating the problem and missing simpler solutions like binary search or two-pointer.
- error
Not handling edge cases such as c = 0 correctly.
进阶变体
外企场景- arrow_right_alt
What if the sum of squares must be divisible by a certain number?
- arrow_right_alt
What if negative numbers were allowed for a and b?
- arrow_right_alt
What if the problem asked for more than two squares to sum up to c?