2016校招编程题<一>

     一个长度为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>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值