输入一个已经按升序排序过的数组和一个数字,在数组中查找两个数,使得它们的和正好是输入的那个数字。要求时间复杂度是O(n)。
如果有多对数字的和等于输入的数字,输出任意一对即可。
例如:输入数组1、2、4、7、11、15和数字15。由于4+11=15,因此输出4和11。
#include <assert.h>
#include <iostream>
using namespace std;
bool OutputProperlyValue(const int *pA, int nSize, int nKey)
{
assert(NULL != pA || nSize > 0);
int i32First = 0, i32End = nSize - 1;
for (; i32First < i32End; )
{
if (pA[i32End] >= nKey)
{
i32End--;
}
else if ((pA[i32End] + pA[i32First]) < nKey)
{
i32First++;
}
else if ((pA[i32End] + pA[i32First]) > nKey)
{
i32End--;
}
else
{
cout << "两个元素和为" << nKey << "的值的数组元素为:" << pA[i32First] << "和" << pA[i32End] << endl;
break;
}
}
if (i32First >= i32End)
return false;
return true;
}
int main()
{
int aryT[] = {1, 2, 4, 7, 11, 15};
if (!OutputProperlyValue(aryT, (sizeof(aryT)/sizeof (int)), 14))
{
cout << "数组里没有合适的值" << endl;
}
return 0;
}
如果需要输出所有和等于输入的数字的数字对,则可以进行如下的修改。
while(i32First < i32End)
{
if (pA[i32End] >= nKey)
{
i32End--;
}
else if ((pA[i32End] + pA[i32First]) < nKey)
{
i32First++;
}
else if ((pA[i32End] + pA[i32First]) > nKey)
{
i32End--;
}
else
{
cout << "两个元素和为" << nKey << "的值的数组元素为:" << pA[i32First] << "和" << pA[i32End] << endl;
i32First++;
i32End--;
if (i32First >= i32End)
return true;
}
}