【题目描述】
Given an integer array, find a subarray where the sum of numbers iszero. Your code should return the index of the first number and the index of the last number.
Notice:
There is at least one subarray that it's sum equals to zero.
给定一个整数数组,找到和为零的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置
【注】:至少有一个阵,它的总和等于零。
【题目链接】
www.lintcode.com/en/problem/subarray-sum/
【题目解析】
题目中的对象是分析子串和,那么我们先从常见的对数组求和出发,f(i)=∑0inums[i] 表示从数组下标 0 开始至下标 i 的和。子串和为0,也就意味着存在不同的 i1 和 i2 使得 f(i1)−f(i2)=0, 等价于 f(i1)=f(i2). 思路很快就明晰了,使用一 vector 保存数组中从 0 开始到索引i的和,在将值push 进 vector 之前先检查 vector 中是否已经存在,若存在则将相应索引加入最终结果并返回。
【参考答案】
www.jiuzhang.com/solutions/subarray-sum/
转载于:https://blog.51cto.com/13457813/2056046