LeetCode 题解工作台
找出中枢整数
给你一个正整数 n ,找出满足下述条件的 中枢整数 x : 1 和 x 之间的所有元素之和等于 x 和 n 之间所有元素之和。 返回中枢整数 x 。如果不存在中枢整数,则返回 -1 。题目保证对于给定的输入,至多存在一个中枢整数。 示例 1: 输入: n = 8 输出: 6 解释: 6 是中枢整数,…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 前缀和
答案摘要
我们可以直接在 的范围内枚举 ,判断以下等式是否成立。若成立,则 为中枢整数,直接返回 即可。 $$
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 前缀和 题型思路
题目描述
给你一个正整数 n ,找出满足下述条件的 中枢整数 x :
1和x之间的所有元素之和等于x和n之间所有元素之和。
返回中枢整数 x 。如果不存在中枢整数,则返回 -1 。题目保证对于给定的输入,至多存在一个中枢整数。
示例 1:
输入:n = 8 输出:6 解释:6 是中枢整数,因为 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21 。
示例 2:
输入:n = 1 输出:1 解释:1 是中枢整数,因为 1 = 1 。
示例 3:
输入:n = 4 输出:-1 解释:可以证明不存在满足题目要求的整数。
提示:
1 <= n <= 1000
解题思路
方法一:枚举
我们可以直接在 的范围内枚举 ,判断以下等式是否成立。若成立,则 为中枢整数,直接返回 即可。
时间复杂度 ,其中 为给定的正整数 。空间复杂度 。
class Solution:
def pivotInteger(self, n: int) -> int:
for x in range(1, n + 1):
if (1 + x) * x == (x + n) * (n - x + 1):
return x
return -1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(1) |
| 空间 | Since the input size (in terms of bits) is bounded by a constant multiple of |
面试官常问的追问
外企场景- question_mark
Checks if the candidate understands the relation between prefix sums.
- question_mark
Evaluates if the candidate can apply an efficient mathematical formula.
- question_mark
Assesses how the candidate handles edge cases like n = 1 or no pivot integer.
常见陷阱
外企场景- error
Ignoring the need for an efficient solution beyond brute force.
- error
Overcomplicating the problem with unnecessary calculations.
- error
Missing edge cases where no pivot integer exists.
进阶变体
外企场景- arrow_right_alt
Handling cases where no pivot integer exists.
- arrow_right_alt
Optimizing for larger values of n (up to 1000).
- arrow_right_alt
Extending the problem to larger ranges of n or different sum conditions.