[LeetCode] 2485. Find the Pivot Integer

Given a positive integer n, find the pivot integer x such that:

  • The sum of all elements between 1 and x inclusively equals the sum of all elements between x and n inclusively.

Return the pivot integer x. If no such integer exists, return -1. It is guaranteed that there will be at most one pivot index for the given input.

Example 1:

Input: n = 8
Output: 6
Explanation: 6 is the pivot integer since: 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21.

Example 2:

Input: n = 1
Output: 1
Explanation: 1 is the pivot integer since: 1 = 1.

Example 3:

Input: n = 4
Output: -1
Explanation: It can be proved that no such integer exist. 

Constraints:

  • 1 <= n <= 1000

找出中枢整数。

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

1 和 x 之间的所有元素之和等于 x 和 n 之间所有元素之和。
返回中枢整数 x 。如果不存在中枢整数,则返回 -1 。题目保证对于给定的输入,至多存在一个中枢整数。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-the-pivot-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这是一道数学题,请你找到一个比 n 小的数字 x,满足 1 + 2 + 3 + ... + x  = x + (x + 1) + (x + 2) + ... + n。

小学数学告诉我们(首项 + 末项)* 项数 / 2 = 一个连续数组的和,我们把它记为 total。接着我们从 1 遍历到 n,同时记录从 1 到 n 的前缀和,看看计算到哪个数字的时候能满足题目给的公式,即左半边的和 = 右半边。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int pivotInteger(int n) {
 3         int total = (1 + n) * n / 2;
 4         int sum = 0;
 5         for (int i = 1; i <= n; i++) {
 6             sum += i;
 7             if (sum == total - sum + i) {
 8                 return i;
 9             }
10         }
11         return -1;
12     }
13 }

 

LeetCode 题目总结

posted @ 2023-06-26 23:09  CNoodle  阅读(52)  评论(0编辑  收藏  举报