前缀和代码

This commit is contained in:
3119005212
2021-04-27 15:11:05 +08:00
parent e8255d73ec
commit 8ef63207ac
5 changed files with 170 additions and 2 deletions

View File

@@ -61,6 +61,8 @@
理解了我们前缀和的概念不知道好像也可以做这个题太简单了哈哈我们可以一下就能把这个题目做出来先遍历一遍求出数组的和然后第二次遍历时直接进行对比左半部分和右半部分是否相同如果相同则返回 true不同则继续遍历
Java Code:
```java
class Solution {
public int pivotIndex(int[] nums) {
@@ -82,4 +84,27 @@ class Solution {
}
```
###
C++ Code:
```cpp
class Solution {
public:
int pivotIndex(vector<int>& nums) {
int presum = 0;
//数组的和
for (int x : nums) {
presum += x;
}
int leftsum = 0;
for (int i = 0; i < nums.size(); ++i) {
//发现相同情况
if (leftsum == presum - nums[i] - leftsum) {
return i;
}
leftsum += nums[i];
}
return -1;
}
};
```