LeetCode 题解工作台
找到和为给定整数的三个连续整数
给你一个整数 num ,请你返回三个连续的整数,它们的 和 为 num 。如果 num 无法被表示成三个连续整数的和,请你返回一个 空 数组。 示例 1: 输入: num = 33 输出: [10,11,12] 解释: 33 可以表示为 10 + 11 + 12 = 33 。 10, 11, 12 …
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数学·结合·模拟
答案摘要
我们假设三个连续的整数分别为 , , ,则它们的和为 ,因此 必须是 的倍数。如果 不是 的倍数,则无法表示成三个连续整数的和,返回空数组。否则,令 $x = \frac{\textit{num}}{3}$,则 , , 就是三个连续整数,它们的和为 。 时间复杂度 ,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·结合·模拟 题型思路
题目描述
给你一个整数 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
解题思路
方法一:数学
我们假设三个连续的整数分别为 , , ,则它们的和为 ,因此 必须是 的倍数。如果 不是 的倍数,则无法表示成三个连续整数的和,返回空数组。否则,令 ,则 , , 就是三个连续整数,它们的和为 。
时间复杂度 ,空间复杂度 。
class Solution:
def sumOfThree(self, num: int) -> List[int]:
x, mod = divmod(num, 3)
return [] if mod else [x - 1, x, x + 1]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.