LeetCode 题解工作台

找到和为给定整数的三个连续整数

给你一个整数 num ,请你返回三个连续的整数,它们的 和 为 num 。如果 num 无法被表示成三个连续整数的和,请你返回一个 空 数组。 示例 1: 输入: num = 33 输出: [10,11,12] 解释: 33 可以表示为 10 + 11 + 12 = 33 。 10, 11, 12 …

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 数学·结合·模拟

bolt

答案摘要

我们假设三个连续的整数分别为 , , ,则它们的和为 ,因此 必须是 的倍数。如果 不是 的倍数,则无法表示成三个连续整数的和,返回空数组。否则,令 $x = \frac{\textit{num}}{3}$,则 , , 就是三个连续整数,它们的和为 。 时间复杂度 ,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·结合·模拟 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数 num ,请你返回三个连续的整数,它们的  为 num 。如果 num 无法被表示成三个连续整数的和,请你返回一个  数组。

 

示例 1:

输入:num = 33
输出:[10,11,12]
解释:33 可以表示为 10 + 11 + 12 = 33 。
10, 11, 12 是 3 个连续整数,所以返回 [10, 11, 12] 。

示例 2:

输入:num = 4
输出:[]
解释:没有办法将 4 表示成 3 个连续整数的和。

 

提示:

  • 0 <= num <= 1015
lightbulb

解题思路

方法一:数学

我们假设三个连续的整数分别为 x1x-1, xx, x+1x+1,则它们的和为 3x3x,因此 num\textit{num} 必须是 33 的倍数。如果 num\textit{num} 不是 33 的倍数,则无法表示成三个连续整数的和,返回空数组。否则,令 x=num3x = \frac{\textit{num}}{3},则 x1x-1, xx, x+1x+1 就是三个连续整数,它们的和为 num\textit{num}

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
5
class Solution:
    def sumOfThree(self, num: int) -> List[int]:
        x, mod = divmod(num, 3)
        return [] if mod else [x - 1, x, x + 1]
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Understand if the candidate can recognize and leverage patterns in number theory.

  • question_mark

    Evaluate the candidate's ability to quickly derive a mathematical approach and apply it in simulation.

  • question_mark

    Check if the candidate can handle edge cases, such as small or large values of num.

warning

常见陷阱

外企场景
  • error

    Failing to recognize the mathematical relationship between three consecutive numbers and their sum.

  • error

    Overcomplicating the solution by trying unnecessary loops or searches.

  • error

    Not correctly handling edge cases, like when num is too small or large for a valid solution.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Generalizing the problem to find n consecutive integers that sum to a given number.

  • arrow_right_alt

    Changing the number of integers to sum (e.g., four or five consecutive integers).

  • arrow_right_alt

    Adding constraints such as finding consecutive prime numbers that sum to a given number.

help

常见问题

外企场景

找到和为给定整数的三个连续整数题解:数学·结合·模拟 | LeetCode #2177 中等