Find subarray with given sum

问题:Given an unsorted array of integers, find a continous subarray which adds to a given number.

注意:数组中有正有负。

参见:http://stackoverflow.com/questions/5534063/zero-sum-subarray


#include<cstdio>
#include<map>
#include<string.h>
using namespace std;

bool findsub(int A[], int n, int target, int &left, int &right)
{
	if(n == 0)
		return false;
	
	multimap<int, int> sum;
	int *tmp = new int[n+1]; //tmp[i] 表示前i项之和
	tmp[0] = 0;
	for(int i=1;i<=n;i++)
	{
		tmp[i] = tmp[i-1] + A[i-1];
		sum.insert(pair<int,int>(tmp[i], i));
	}
    
	int i;
	for(i=0;i<=n;i++)
	{
        multimap<int, int>::iterator it = sum.find(tmp[i] + target);
        if(it == sum.end())
            continue;
		for(;(*it).first == tmp[i] + target;it++)
		{
            right = (*it).second;
            if(right <= i)
                continue;
            left = i+1;
            return true;
		}
	}
	return false;
}


int main()
{
    int A[10002];
	int n, target;
	int left, right;
	while(scanf("%d",&n)!=EOF)
	{
		for(int i=0;i<n;i++)
			scanf("%d", &A[i]);
		scanf("%d",&target);
		if(findsub(A, n, target, left, right))
			printf("%d %d\n",left, right);
		else
			printf("No\n");
	}
	return 1;
}


你可能感兴趣的:(Find subarray with given sum)