找出中枢整数
难度:
标签:
题目描述
Given a positive integer n
, find the pivot integer x
such that:
- The sum of all elements between
1
andx
inclusively equals the sum of all elements betweenx
andn
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
代码结果
运行时间: 26 ms, 内存: 16.0 MB
// Java Stream Solution
// 思路:
// 1. 计算1到n之间所有整数的总和totalSum。
// 2. 使用Java Stream遍历1到n之间的整数,计算左侧和右侧的和,检查是否存在中枢整数。
import java.util.stream.IntStream;
public class PivotIntegerStream {
public int findPivot(int n) {
int totalSum = IntStream.rangeClosed(1, n).sum();
return IntStream.rangeClosed(1, n)
.filter(x -> IntStream.rangeClosed(1, x).sum() == totalSum - IntStream.rangeClosed(1, x).sum())
.findFirst()
.orElse(-1);
}
}
解释
方法:
该题解的整体思路是通过迭代找出中枢整数x。首先,计算从1到n的总和total。然后,通过一个循环逐步计算从1到当前值value的累加和current,同时从total中减去当前的value,以此模拟两侧的和。如果在某一点,current等于total,那么这一点就是中枢整数x。如果循环结束后没有找到这样的点,返回-1。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
如何确定题目中的'中枢整数'定义是否需要包含该整数本身在内的累加和?
▷🦆
在计算total时,直接使用了(1 + n) * n / 2的公式,这个公式是如何得来的,它代表什么意义?
▷🦆
在循环中,current和total都在同步更新,有没有可能出现在不同的value值时,current等于total的情况?
▷