1 /************************************************************************* 2 > File Name: 39_TwoNumbersWithSum.cpp 3 > Author: Juntaran 4 > Mail: [email protected] 5 > Created Time: 2016年09月03日 星期六 11时14分49秒 6 ************************************************************************/ 7 8 #include <stdio.h> 9 10 bool FindNumberWithSum(int* nums, int length, int sum, int* num1, int* num2) 11 { 12 bool ret = false; 13 if (length<1 || num1==NULL || num2==NULL) 14 return ret; 15 16 int left = 0; 17 int right = length - 1; 18 19 while (right > left) 20 { 21 int current = nums[left] + nums[right]; 22 if (current == sum) 23 { 24 *num1 = nums[left]; 25 *num2 = nums[right]; 26 ret = true; 27 return ret; 28 } 29 else if (current > sum) 30 right --; 31 else 32 left ++; 33 } 34 return ret; 35 } 36 37 int main() 38 { 39 int nums[] = {1,2,4,7,11,15}; 40 int length = 6; 41 int sum = 15; 42 int num1, num2; 43 44 if (FindNumberWithSum(nums, length, sum, &num1, &num2)) 45 printf("%d, %d\n", num1, num2); 46 else 47 printf("Not Find\n"); 48 return 0; 49 }
时间: 2024-11-15 19:40:25