Skip to content

Commit 8ca203d

Browse files
authored
Create find-the-middle-index-in-array.cpp
1 parent 16e9c52 commit 8ca203d

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int findMiddleIndex(vector<int>& nums) {
7+
const int total = accumulate(cbegin(nums), cend(nums), 0);
8+
int accu = 0;
9+
for (int i = 0; i < size(nums); ++i) {
10+
if (accu * 2 == total - nums[i]) {
11+
return i;
12+
}
13+
accu += nums[i];
14+
}
15+
return -1;
16+
}
17+
};

0 commit comments

Comments
 (0)