Find zero pairs

Question :
Design and implement an algorithm (C++ function) that, given an array of integers, determines whether the sum of any two distinct elements is zero. Assume, of course, that there might be positive and negative values in the array (i.e. don't just look for a pair of zeroes!).

test IDE: Microsoft Visual Studio 2005

test OS:Microsoft Windows 7

The code as following may solve this problem:

#include "stdafx.h"
#include <iostream>
#include <algorithm>
void FindZeroPairs(int data[], int nLen)
{
	int pLeft = 0;
	int pRight = nLen - 1;
	while (pLeft < pRight)
	{
		if (0 == data[pLeft] + data[pRight])
		{
			printf("Zero pair: %d and %d\n", data[pLeft], data[pRight]);
			--pRight;
			++pLeft;
			continue;
		}
		if (0 < data[pLeft] + data[pRight])
		{
			--pRight;
			continue;
		}
		if (0 > data[pLeft] + data[pRight])
		{
			++pLeft;
		}
	}
}


int _tmain(int argc, _TCHAR* argv[])
{
	int nLen;
	printf("Input length of integer array:");
	scanf("%d", &nLen);
	// allocate space for array with length of nLen
	int *pData = new int[nLen];
	int i = 0;
	while (i < nLen)
	{
		scanf("%d", &pData[i]);
		++i;
	}
	// sort array
	std::sort(pData, pData + nLen);
	for (int i = 0; i < nLen; ++i)
	{
		printf("%d ", pData[i]);
	}
	printf("\n");

	FindZeroPairs(pData, nLen);
	return 0;
}




你可能感兴趣的:(Find zero pairs)