algorithm-base/animation-simulation/前缀和/leetcode724寻找数组的中心索引.md

111 lines
4.8 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
###
Sn = a1+a2+a3+...an; Sn n S5 = a1 + a2 + a3 + a4 + a5; S2 = a1 + a2 S5-S2 a3+a4+a5 n
![](https://cdn.jsdelivr.net/gh/tan45du/github.io.phonto2@master/myphoto/微信截图_20210113193831.4wk2b9zc8vm0.png)
n presum[1] nums 1 **presum[1]** = nums[0], **presum[2]** = nums[0] + nums[1] = **presum[1]** + nums[1].
nums[2] nums[4] presum BM,KMP next suffix presum nums[2] nums[4]
![](https://cdn.jsdelivr.net/gh/tan45du/github.io.phonto2@master/myphoto/前缀和.77twdj3gpkg0.png)
```java
for (int i = 0; i < nums.length; i++) {
presum[i+1] = nums[i] + presum[i];
}
```
#### [724. ](https://leetcode-cn.com/problems/find-pivot-index/)
****
> nums
>
>
>
> -1
** 1**
>
> nums = [1, 7, 3, 6, 5, 6]
> 3
3 (nums[3] = 6) (1 + 7 + 3 = 11) (5 + 6 = 11)
, 3
** 2**
>
> nums = [1, 2, 3]
> -1
true
Java Code:
```java
class Solution {
public int pivotIndex(int[] nums) {
int presum = 0;
//数组的和
for (int x : nums) {
presum += x;
}
int leftsum = 0;
for (int i = 0; i < nums.length; ++i) {
//发现相同情况
if (leftsum == presum - nums[i] - leftsum) {
return i;
}
leftsum += nums[i];
}
return -1;
}
}
```
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;
}
};
```