JZ-C-41
剑指offer第四十一题:和为s的两个数字:输入一个递增排序的数组和一个数字,在数组中查找两个数,使得它们的和正好等于s。若有多对,输出任意一对即可
1 //============================================================================ 2 // Name : JZ-C-41.cpp 3 // Author : Laughing_Lz 4 // Version : 5 // Copyright : All Right Reserved 6 // Description :和为s的两个数字:输入一个递增排序的数组和一个数字,在数组中查找两个数,使得它们的和正好等于s。若有多对,输出任意一对即可 7 //============================================================================ 8 9 #include <iostream> 10 #include <stdio.h> 11 using namespace std; 12 13 bool FindNumbersWithSum(int data[], int length, int sum, int* num1, int* num2) { 14 bool found = false; 15 if (length < 1 || num1 == NULL || num2 == NULL) 16 return found; 17 18 int ahead = length - 1; 19 int behind = 0; 20 21 while (ahead > behind) { 22 long long curSum = data[ahead] + data[behind]; 23 24 if (curSum == sum) { 25 *num1 = data[behind]; 26 *num2 = data[ahead]; 27 found = true; 28 break; 29 } else if (curSum > sum) 30 ahead--; 31 else 32 behind++; 33 } 34 35 return found; 36 } 37 38 // ====================测试代码==================== 39 void Test(char* testName, int data[], int length, int sum, 40 bool expectedReturn) { 41 if (testName != NULL) 42 printf("%s begins: ", testName); 43 44 int num1, num2; 45 int result = FindNumbersWithSum(data, length, sum, &num1, &num2); 46 if (result == expectedReturn) { 47 if (result) { 48 if (num1 + num2 == sum) 49 printf("Passed. \n"); 50 else 51 printf("Failed. \n"); 52 } else 53 printf("Passed. \n"); 54 } else 55 printf("Failed. \n"); 56 } 57 58 // 存在和为s的两个数字,这两个数字位于数组的中间 59 void Test1() { 60 int data[] = { 1, 2, 4, 7, 11, 15 }; 61 Test("Test1", data, sizeof(data) / sizeof(int), 15, true); 62 } 63 64 // 存在和为s的两个数字,这两个数字位于数组的两段 65 void Test2() { 66 int data[] = { 1, 2, 4, 7, 11, 16 }; 67 Test("Test2", data, sizeof(data) / sizeof(int), 17, true); 68 } 69 70 // 不存在和为s的两个数字 71 void Test3() { 72 int data[] = { 1, 2, 4, 7, 11, 16 }; 73 Test("Test3", data, sizeof(data) / sizeof(int), 10, false); 74 } 75 76 // 鲁棒性测试 77 void Test4() { 78 Test("Test4", NULL, 0, 0, false); 79 } 80 81 int main(int argc, char** argv) { 82 Test1(); 83 Test2(); 84 Test3(); 85 Test4(); 86 87 return 0; 88 }
—————————————————————————————————————行走在人猿的并行线——Laughing_Lz