1991.找到数组的中间位置
链接:1991.找到数组的中间位置
难度:Easy
标签:数组、前缀和
简介:请你返回满足上述条件 最左边 的 middleIndex ,如果不存在这样的中间位置,请你返回 -1 。
题解 1 - cpp
- 编辑时间:2021-12-23
- 内存消耗:12.1MB
- 编程语言:cpp
- 解法介绍:前缀和。
class Solution {
public:
int findMiddleIndex(vector<int>& nums) {
int sum = 0;
for (auto& num : nums) sum += num;
int pre = 0;
for (int i = 0; i < nums.size(); i++) {
if (sum - nums[i] == pre) return i;
pre += nums[i];
sum -= nums[i];
}
return -1;
}
};