problem - 14
1 /* 2 problem: 输入一个以按升序排列的数组, 和一个数字 3 demand: 在数组中查找两个数, 使得他们的和正好是输入的那个数字, 要求 O(n) 时间复杂度. 如果有多对, 输出一对即可. 4 eg. 1 2 4 7 11 15 输入数字 15, 输出 4 11 5 */ 6 7 #include <iostream> 8 using namespace std; 9 10 void find2Number(int arr[], int n, int dest); 11 12 #define N 6 13 14 int main(void) 15 { 16 int arr[N] = {1, 2, 4, 7, 11, 15}; 17 find2Number(arr, N, 15); 18 return 0; 19 } 20 21 void find2Number(int arr[], int n, int dest) 22 { 23 int* head = arr; 24 int* tail = arr + n -1; 25 while ( head != tail ) { 26 if ( *head + *tail > dest ) 27 --tail; 28 else if ( *head + *tail < dest ) 29 ++head; 30 else { 31 cout<< *head <<" "<< *tail << endl; 32 break; 33 } 34 } 35 if ( *head == *tail ) 36 cout<< "not found" <<endl; 37 }