一个长度为N的数组中包含正数,负数和0,请实现一个函数找出最长和为零的连续子数组。
输入:所有数组元素在一行,空格隔开
输出:所有数组元素在一行,空格隔开
输出:所有数组元素在一行,空格隔开
输入样例:1 2 3 4 -1 -2 -4 -3 1 2
输出样例:1 2 3 4 -1 -2 -4 -3
<span style="font-size:18px;">#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string str;
getline(cin, str);
vector<int> arr;
vector<int> sum;
int sumIndex = 0;
sum.push_back(0);
int index = 0;
int nextIndex = 0;
int n;
string tmp;
while(index != -1)
{
if(index == 0)
{
nextIndex = str.find(' ', index);
tmp = str.substr(index, nextIndex-index);
}else{
nextIndex = str.find(' ', index+1);
tmp = str.substr(index+1, nextIndex-index-1);
}
int itemp = std::atoi(tmp.c_str());
arr.push_back(itemp);
n = itemp + sum[sumIndex];
sum.push_back(n);
sumIndex++;
index = nextIndex;
}
int minIndex = 0;
int maxIndex = 0;
int maxLen = 0;
for (int i = 0; i < sum.size(); i++)
{
for (int j = sum.size()-1; j > i + maxLen; j--)
{
if(sum[i] == sum[j])
{
maxLen = j - i;
minIndex = i;
maxIndex = j;
}
}
}
for (int i = minIndex; i < maxIndex; i++)
{
cout << arr[i] << ' ';
}
return 0;
}
</span>