LeetCode 题解工作台
连续整数求和
给定一个正整数 n ,返回 连续正整数满足所有数字之和为 n 的组数 。 示 例 1: 输入: n = 5 输出: 2 解释: 5 = 2 + 3,共有两组连续整数([5],[2,3])求和后为 5。 示例 2: 输入: n = 9 输出: 3 解释: 9 = 4 + 5 = 2 + 3 + 4 示…
2
题型
5
代码语言
3
相关题
当前训练重点
困难 · 数学·结合·enumeration
答案摘要
连续正整数构成一个公差 $d = 1$ 的等差数列。我们假设等差数列的第一项为 ,项数为 ,那么 $n = (a + a + k - 1) \times k / 2$,即 $n \times 2 = (a \times 2 + k - 1) \times k$。这里我们可以得出 一定能整除 $n \times 2$,并且 $(n \times 2) / k - k + 1$ 一定是偶数。 由于 …
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·结合·enumeration 题型思路
题目描述
给定一个正整数 n,返回 连续正整数满足所有数字之和为 n 的组数 。
示例 1:
输入: n = 5 输出: 2 解释: 5 = 2 + 3,共有两组连续整数([5],[2,3])求和后为 5。
示例 2:
输入: n = 9 输出: 3 解释: 9 = 4 + 5 = 2 + 3 + 4
示例 3:
输入: n = 15 输出: 4 解释: 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5
提示:
1 <= n <= 109
解题思路
方法一:数学推导
连续正整数构成一个公差 的等差数列。我们假设等差数列的第一项为 ,项数为 ,那么 ,即 。这里我们可以得出 一定能整除 ,并且 一定是偶数。
由于 ,所以 。
综上,我们可以得出:
- 一定能整除 ;
- ;
- 一定是偶数。
我们从 开始枚举,当 时,我们可以结束枚举。在枚举的过程中,我们判断 是否能整除 ,并且 是否是偶数,如果是则满足条件,答案加一。
枚举结束后,返回答案即可。
时间复杂度 ,其中 为给定的正整数。空间复杂度 。
class Solution:
def consecutiveNumbersSum(self, n: int) -> int:
n <<= 1
ans, k = 0, 1
while k * (k + 1) <= n:
if n % k == 0 and (n // k + 1 - k) % 2 == 0:
ans += 1
k += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate quickly recognize the mathematical pattern behind consecutive sums?
- question_mark
Does the candidate efficiently handle large inputs (up to 10^9)?
- question_mark
Is the candidate able to optimize the solution by reducing unnecessary checks or calculations?
常见陷阱
外企场景- error
Forgetting that the starting number must be positive, which could lead to invalid sequences.
- error
Misunderstanding the sum formula for consecutive integers, leading to incorrect solutions.
- error
Not optimizing the solution by stopping once k exceeds sqrt(n), resulting in inefficient solutions.
进阶变体
外企场景- arrow_right_alt
Can this problem be generalized to find all sequences for a range of numbers?
- arrow_right_alt
How would the approach change if negative integers were allowed?
- arrow_right_alt
What if the sequence must include at least three integers instead of two?