
2026-05-17:中心子数组的数量。用go语言,给定一个整数数组 nums。
考虑数组中的任意一个连续非空子数组。若该子数组的“总和”恰好等于该子数组中“至少一个元素的值”,则称这个子数组为中心子数组。
你的任务是:统计 nums 中所有中心子数组的数量,并返回这个数量。
1 <= nums.length <= 500。
-100000 <= nums[i] <= 100000。
输入: nums = [-1,1,0]。
输出: 5。
解释:
所有单元素子数组([-1],[1],[0])都是中心子数组。
子数组 [1, 0] 的元素之和为 1,且 1 存在于该子数组中。
子数组 [-1, 1, 0] 的元素之和为 0,且 0 存在于该子数组中。
因此,答案是 5。
题目来自力扣3804。
数组长度为3,总共有 6个 连续非空子数组(所有可能的连续片段):
[-1](起始索引0,结束索引0)[-1,1](起始索引0,结束索引1)[-1,1,0](起始索引0,结束索引2)[1](起始索引1,结束索引1)[1,0](起始索引1,结束索引2)[0](起始索引2,结束索引2)代码的核心逻辑是:固定子数组的起点,依次扩展终点,遍历所有子数组,同时用哈希表记录当前子数组包含的元素,快速判断「总和是否存在于子数组中」。
从第一个元素开始,逐步向右扩展子数组:
清空之前的记录,从第二个元素开始扩展:
清空之前的记录,从第三个元素开始扩展:
所有符合条件的中心子数组:
.
package main
import (
"fmt"
)
func centeredSubarrays(nums []int) (ans int) {
has := map[int]int{}
for i := range nums {
clear(has)
s := 0
for _, x := range nums[i:] {
has[x] = 1
s += x
ans += has[s]
}
}
return
}
func main() {
nums := []int{-1, 1, 0}
result := centeredSubarrays(nums)
fmt.Println(result)
}

.
# -*-coding:utf-8-*-
def centeredSubarrays(nums):
ans = 0
n = len(nums)
for i in range(n):
has = {}
s = 0
for j in range(i, n):
x = nums[j]
has[x] = 1
s += x
ans += has.get(s, 0)
return ans
def main():
nums = [-1, 1, 0]
result = centeredSubarrays(nums)
print(result)
if __name__ == "__main__":
main()
.
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int centeredSubarrays(vector<int>& nums) {
int ans = 0;
unordered_map<int, int> has;
for (int i = 0; i < nums.size(); i++) {
has.clear();
int s = 0;
for (int j = i; j < nums.size(); j++) {
int x = nums[j];
has[x] = 1;
s += x;
ans += has[s]; // 如果 s 不存在于 map 中,has[s] 会返回 0
}
}
return ans;
}
int main() {
vector<int> nums = {-1, 1, 0};
int result = centeredSubarrays(nums);
cout << result << endl;
return0;
}
