/*题目1:输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于
s,输出任意一对即可。
题目2:输入一个正数,打印出所有和为s的连续正数序列(至少含有两个数)。例如输入15, 由于1 + 2 + 3 + 4 + 5 =
4 + 5 + 6 = 7 + 8 = 15, 所以结果打印出3个连续序列1 ~ 5, 4 ~ 6和7 ~ 8。*/
#include <iostream>
using namespace std;
//和为Sum的两个数字
bool FindTwoNumbersWithSum(int data[], int nlength, int &num1, int &num2, int Sum)
{
bool found = false;
if(data == NULL || nlength < 1)
return found;
int aHead = 0;
int Behind = nlength - 1;
while(aHead < Behind)
{
int curSum = data[aHead] + data[Behind];
if(curSum == Sum)
{
num1 = data[aHead];
num2 = data[Behind];
found = true;
break;
}else if(curSum < Sum)
aHead++;
else
--Behind;
}
return found;
}
//输出连续数字
void PrintContinousSequence(int small, int big)
{
while(small <= big)
{
cout << small << " ";
++small;
}
cout << endl;
}
//和为Sum的连续整数序列
void FindNumbersWithContinuousSequence(int Sum)
{
if(Sum < 3)
return;
//初始化
int small = 1;
int big = 2;
int curSum = small + big;
int middle = (Sum + 1) / 2;
while(small < middle)
{
if(curSum == Sum)
PrintContinousSequence(small, big);
while(curSum < Sum && small < middle)
{
big++;
curSum += big;
if(curSum == Sum)
PrintContinousSequence(small, big);
}
curSum -= small;
small++;
}
}
//=======================测试代码====================
void Test(char *TestName, int data[], int nlength, int Sum, bool Expected)
{
if(TestName != NULL)
cout << TestName << " Begins:" << endl;
int num1 = 0;
int num2 = 0;
bool Result = FindTwoNumbersWithSum(data, nlength, num1, num2, Sum);
if(Result == Expected)
{
if(Result)
{
if(num1 + num2 == Sum)
cout << "Passed!" << endl;
else
cout << "Failed!" << endl;
}else
cout << "Passed!" << endl;
}
else
cout << "Failed!" << endl;
}
//=======================测试代码B===========================
void TestB(char *TestName, int Sum)
{
if(TestName != NULL)
cout << TestName << " for " << Sum << " Begins:" << endl;
FindNumbersWithContinuousSequence(Sum);
}
//=====================测试用例========================
//存在和为Sum的数对,且在数组中间
void Test1()
{
int data[] = {1, 2, 4, 7, 11, 15};
Test("Test1", data, sizeof(data) / sizeof(int), 15, true);
}
//存在和为Sum的数对且在数组两端
void Test2()
{
int data[] = {1, 2, 4, 7, 11, 16};
Test("Test2", data, sizeof(data) / sizeof(int), 17, true);
}
//不存在和为Sum的数对
void Test3()
{
int data[] = {1, 2, 4, 7, 11, 16};
Test("Test3", data, sizeof(data) / sizeof(int), 10, false);
}
//鲁棒性测试
void Test4()
{
Test("Test4", NULL, 0, 10, false);
}
int main()
{
Test1();
Test2();
Test3();
Test4();
TestB("Test1", 1);
TestB("Test2", 3);
TestB("Test3", 4);
TestB("Test4", 9);
TestB("Test5", 15);
TestB("Test6", 100);
return 0;
}
面试题41:和为s的两个数字VS和为s的连续正数序列
最新推荐文章于 2021-05-20 13:14:51 发布