求两个数和为s,判断它是否在数组中存在,并且数组已经排好序

//和为s的两个数字(数字已经按照递增序列排列)
bool FindNumberWithSum(int data[], int length, int sum, int *num1, int *num2)
{
	bool found = false;
	if (length < 1 || num2 == NULL || num1 == NULL || data == NULL)
		return found;
	int ahead = length - 1;
	int behind = 0;

	while (ahead > behind)
	{
		long long curSum = data[ahead] + data[behind];
		if (curSum == sum)
		{
			*num1 = data[behind];
			*num2 = data[ahead];
			found = true;
			break;
		}
		else if (curSum > sum)
		{
			ahead = ahead - 1;
		}
		else
		{
			behind = behind + 1;
		}
	}
	return found;
}

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页