[LeetCode] 633. Sum of Square Numbers_Medium tag: Binary Search, Enumeration
2026-11-27 06:33
Johnson_强生仔仔
阅读(4)
评论(0)
收藏
举报
LeetCode 633 · Binary Search 系统总结
Problem
Given a non-negative integer c, determine whether there are integers a and b such that a² + b² = c.
c = 5 -> True (1² + 2² = 5)
c = 3 -> False
Constraints: 0 <= c <= 2³¹ - 1.
思路:枚举一个数,二分判断剩余值
要区分“枚举整数 a”和“枚举平方值 a²”。如果直接枚举 a,那么 a² 已经是完全平方数,不需要再检查一次;只需判断 c - a² 是否为另一个整数的平方。
从 a=0 开始,只要 a * a <= c 就继续。对于剩余值 target,函数 judgeSquare(target) 使用 binary search 寻找整数 b:若 b² < target 则向右找,若 b² > target 则向左找,相等就找到答案。
例如 c=5:a=0 时剩余5,不是完全平方数;a=1 时剩余4,是2²,因此返回 True。平方数的根也可以为0,不能把这种情况漏掉。
本次实现
下面保留练习时写出的版本。主循环从1开始也正确:0和1单独处理;如果c本身是完全平方数,遍历到 i² == c 时剩余0,helper返回True,仍能识别 sqrt(c)² + 0²。
class Solution:
def judgeSquareSum(self, c: int) -> bool:
if 0 <= c <= 1:
return True
i = 1
while i * i <= c:
if self.judgeSquare(c - i * i):
return True
i += 1
return False
def judgeSquare(self, c: int) -> bool:
if c in [0, 1]:
return True
if c in [2, 3]:
return False
l, r = 2, c // 2
while l + 1 < r:
mid = l + (r - l) // 2
mid_sq = mid * mid
if mid_sq == c:
return True
elif mid_sq < c:
l = mid
else:
r = mid
return l * l == c or r * r == c
Time and space complexity
Time: O(√c × log c)(讨论c增长时的上界)。外层i每次加1,最多枚举到⌊√c⌋;它不是每次减半,所以不是log c。helper的二分搜索每轮减半,单次最多O(log c)。两者相乘。
Auxiliary space: O(1)。使用固定数量的变量,没有额外数组,也没有递归栈。
面试表达:
The outer loop tries at most the square root of c candidates. For each candidate, a binary search checks whether the remainder is a perfect square. Therefore, the time complexity is O(sqrt(c) * log c), and the auxiliary space complexity is O(1).
边界与复习重点
- c=0:0²+0²,True。
- c=1:0²+1²,True。
- c=2:1²+1²,True。
- c=3:False。
- c=4:2²+0²,True。
- c=5:1²+2²,True。
- 不要把外层的“每次加1”误认成二分;复杂度应分别分析每层的次数,再相乘。
- 本次时间复杂度第一次回答为
O(log m * log n),追问外层枚举上界后改正;空间复杂度第一次回答O(1)正确。
本篇归类为Binary Search,是因为当前解法用二分检查完全平方数;也有Enumeration和Math属性。这份笔记总结的是本次实现,并不声称它是所有解法中的最优复杂度。
本文基于本人练习代码及讨论,由 AI 辅助整理。
浙公网安备 33010602011771号