本文最后更新于:2020年7月1日 晚上

题目描述:

输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得它们的和正好是S。如果有多对数字的和等于S,输出任意一对即可

实现如下:

//使用两个指针,分别指向排序数组的第一个元素和最后一个元素,它们是最小值和最大值
//将指针指向的值相加的和与S进行比较
//如果和比S小,则后移前指针
//如果和比S大,则前移后指针
//注意
//1.有可能不存在和为S的两个数,所有路径都有返回值
//2.题目规定乘机最小,其实就是之和最小,也就是第一次相等时的两个元素。。
class Solution 
{
public:
	vector<int> FindNumbersWithSum(vector<int> array, int sum) 
	{
		vector<int> tmp;
		if (array.size() < 2)//防御性动作
			return tmp;
		vector<int>::iterator itBegin = array.begin();//前迭代器
		vector<int>::iterator itEnd = --array.end();//后迭代器
		int count = 0;//记录两个数之和

		while (itBegin < itEnd)//判断有可能不存在和为S的两个数字
		{
			count = *itBegin + *itEnd;
			if (count < sum)//和比S小,后移前指针
				++itBegin;
			else if (count > sum)//和比S大,前移后指针
				--itEnd;
			else//当和相等时,将元素压入序列
			{
				tmp.push_back(*itBegin);
				tmp.push_back(*itEnd);
				break;
			}
		}
		return tmp;
	}
};