题目:
给定一个整数数组,找到和为零的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置。
样例
给出[-3, 1, 2, -3, 4],返回[0, 2] 或者 [1, 3].
解题思路:
依次求数组的前缀和,同时执行如下操作:
假定当前位置是i,查找i之前位置的前缀和,是否存在j位置,使得,j位置的前缀和 等于 i位置的前缀和。
若有,则j 到 i 之间的区间数的和为0.
直到遍历完整个数组。
时间复杂度O(n),空间复杂度O(n).
实现代码:
class Solution {
public:
/**
* @param nums: A list of integers
* @return: A list of integers includes the index of the first number
* and the index of the last number
*/
vector<int> subarraySum(vector<int> nums){
// write your code here
int sum = 0;
vector<int> ret;
unordered_map<int, int> map;
map[0] = -1;
for(int i=0; i<nums.size();i++)
{
sum += nums[i];
if(map.find(sum) != map.end())
{
ret.push_back(map[sum] +1);
ret.push_back(i);
return ret;
}
map[sum] = i;
}
return ret;
}
};
本文介绍了一种高效算法来解决寻找数组中和为零的子数组的问题。通过使用前缀和及哈希表的方法,可以在O(n)的时间复杂度内完成任务,避免了传统方法中的双重循环。

336

被折叠的 条评论
为什么被折叠?



