/******************************************************************* 题目一:输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得他 们的和正好是s。如果有多对数字的和等于s,输出任意一对即可。 *******************************************************************/ /* 解题思路: 设两个指针第一个指针指向数组的第一个,第二个指针指向最后一个。 根据两者之和调整指针指向。当两个指针所指之和等于15时,结束查找。 */ #include<stdio.h> bool findTwoNumbersWithSum(int* s,int length,int sum,int* num1, int* num2) { bool found = false; if(s == NULL || length<=0) return found; int temSum = 0; int smallIndex = 0; int bigIndex = length-1; //寻找符合条件的两个数字 while(smallIndex < bigIndex) { temSum = s[smallIndex]+s[bigIndex]; if(temSum == sum) { found = true; *num1 = s[smallIndex]; *num2 = s[bigIndex]; break; } else if(temSum<sum) ++smallIndex; else --bigIndex; } return found; } void test() { const int length = 6; int s[length] = {1,2,4,7,11,15}; int num1 = 0; int num2 = 0; if(findTwoNumbersWithSum(s,length,15,&num1,&num2)) { printf("%d\t%d\n",num1,num2); } } int main() { test(); return 0; }
原文:http://blog.csdn.net/walkerkalr/article/details/21476259