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

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·搜索·答案·空间

bolt

答案摘要

我们可以使用双指针的方法来解决这个问题,定义两个指针 和 ,分别指向 和 。在每一步中,我们会计算 $s = a^2 + b^2$ 的值,然后比较 与 的大小。如果 $s = c$,我们就找到了两个整数 和 ,使得 $a^2 + b^2 = c$。如果 $s < c$,我们将 的值增加 ,如果 $s > c$,我们将 的值减小 。我们不断进行这个过程直到找到答案,或者 的值大于 …

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

 

示例 1:

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

示例 2:

输入:c = 3
输出:false

 

提示:

  • 0 <= c <= 231 - 1
lightbulb

解题思路

方法一:数学 + 双指针

我们可以使用双指针的方法来解决这个问题,定义两个指针 aabb,分别指向 00c\sqrt{c}。在每一步中,我们会计算 s=a2+b2s = a^2 + b^2 的值,然后比较 sscc 的大小。如果 s=cs = c,我们就找到了两个整数 aabb,使得 a2+b2=ca^2 + b^2 = c。如果 s<cs < c,我们将 aa 的值增加 11,如果 s>cs > c,我们将 bb 的值减小 11。我们不断进行这个过程直到找到答案,或者 aa 的值大于 bb 的值,返回 false

时间复杂度 O(c)O(\sqrt{c}),其中 cc 是给定的非负整数。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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?

help

常见问题

外企场景

平方数之和题解:二分·搜索·答案·空间 | LeetCode #633 中等