【100题】在排序数组中查找和为给定值的两个数

//在排序数组中查找和为给定值的两个数
#include <iostream>
using namespace std;

bool FindNum
(
	int data[],
	unsigned int length,
	int sum,
	int &n1,
	int &n2
 )
{
	bool found =  false;
	if(length < 1)
	{
		return found;
	}
	int ahead = length - 1;
	int behind = 0;

	while(ahead > behind)
	{
		long long curSum = data[ahead]+data[behind];
		//啊哈,找到了。
		if(curSum == sum)
		{
			n1 = data[behind];
			n2 = data[ahead];
			found = true;
			break;
		}
		else if(curSum > sum)
		{//将curSum减小一点。
			ahead--;
		}
		else
		{//将curSum增加一点。
			behind++;
		}
	}
	return found;
}
//测试用例
void main()
{
	int data[] = {1,3,5,7,9,11,15};
	int n1=0;
	int n2=0;
	FindNum(data,sizeof(data)/sizeof(data[0]),20,n1,n2);
	cout << n1 <<" "<<n2<<endl;
}

你可能感兴趣的:(测试,n2)