LeetCode 题解工作台

找出中枢整数

给你一个正整数 n ,找出满足下述条件的 中枢整数 x : 1 和 x 之间的所有元素之和等于 x 和 n 之间所有元素之和。 返回中枢整数 x 。如果不存在中枢整数,则返回 -1 。题目保证对于给定的输入,至多存在一个中枢整数。 示例 1: 输入: n = 8 输出: 6 解释: 6 是中枢整数,…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 前缀和

bolt

答案摘要

我们可以直接在 的范围内枚举 ,判断以下等式是否成立。若成立,则 为中枢整数,直接返回 即可。 $$

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 前缀和 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个正整数 n ,找出满足下述条件的 中枢整数 x

  • 1x 之间的所有元素之和等于 xn 之间所有元素之和。

返回中枢整数 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
lightbulb

解题思路

方法一:枚举

我们可以直接在 [1,..n][1,..n] 的范围内枚举 xx,判断以下等式是否成立。若成立,则 xx 为中枢整数,直接返回 xx 即可。

(1+x)×x=(x+n)×(nx+1)(1 + x) \times x = (x + n) \times (n - x + 1)

时间复杂度 O(n)O(n),其中 nn 为给定的正整数 nn。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
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
speed

复杂度分析

指标
时间O(1)
空间Since the input size (in terms of bits) is bounded by a constant multiple of
psychology

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

找出中枢整数题解:前缀和 | LeetCode #2485 简单