E1-数组的平衡点2(前缀和)
题目描述
给定一个长度为 n 的数组 nums,若其中存在某个位置 index,使得 [0, index - 1] 范围的元素之积 等于 [index + 1, n - 1] 范围的元素之积,则称 index 位置是数组 nums 的平衡点。
请你找出数组 nums 的平衡点位置,若存在多个平衡点位置,则输出最后一个,若不存在平衡点位置,则输出 null。
输入描述
输入一个数组 nums,格式请见用例。数组长度不大于10000。
注意:用例保证乘积结果不会超出 long 范围。不用担心整型溢出问题。数组元素都为 int 类型。
输出描述
输出数组 nums 的平衡点位置,若存在多个平衡点位置,则输出最后一个,若不存在平衡点位置,则输出 null。
用例1
输入
[1, 1, 1, 1, 1]
Copy
输出
4
Copy
说明
若平衡点位置 index = 0,则其左侧范围元素为空,此时认为左侧范围元素之积为1。
若平衡点位置 index = n-1,则其右侧范围元素为空,此时认为右侧范围元素之积为1。
用例2
输入
[2, 5, 3, 6, 5, 6]
Copy
输出
3
Copy
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int M = 1e6 + 10;
vector<int>v;
void solve() {
string str;
getline(cin, str);
str = str.substr(1, str.size() - 2);
size_t pos = 0;
while ((pos = str.find(',')) != string::npos) {
v.push_back(stoi(str.substr(0, pos))); // stoi将字符串转换为整数
str.erase(0, pos + 1); // 删除处理过的部分
}
v.push_back(stoi(str)); // 处理最后一个数字(没有逗号)
int n = v.size();
int sum = v[0];
int res = -1;
int pre[n]; // pre数组存储前缀乘积
pre[0] = v[0];
for (int i = 1; i < n; i++) {
sum *= v[i];
pre[i] = pre[i - 1] * v[i]; // 更新每个位置的前缀乘积
}
for (int i = 0; i < n; i++) {
// 如果当前元素的前缀乘积等于剩余部分的乘积(总乘积/当前前缀乘积),即为平衡点
if (pre[i] == sum / pre[i + 1]) {
res = i; // 记录平衡点位置
}
}
if (res == -1) cout << "null";
else cout << res + 1 << endl;
}
signed main() {
solve();
return 0;
}