问题描述:
1 // 14.cc 2 #include 3 using namespace std; 4 5 bool find_two(int* a, size_t size, int target, int& t1, int& t2) { 6 bool flag = false; 7 if (size < 2) 8 return flag; 9 10 size_t low = 0; 11 size_t high = size - 1; 12 13 while (low < high) { int s = a[low] + a[high]; if (s > target) 14 high--; 15 else if (s < target) 16 low++; 17 else { 18 t1 = a[low]; 19 t2 = a[high]; 20 flag = true; 21 return flag; 22 } 23 } 24 return flag; 25 } 26 27 int main() { 28 int a[] = {1, 3, 4, 5, 13, 17}; 29 int size = sizeof(a) / sizeof(int); 30 int target = 20; 31 int t1, t2; 32 bool flag = find_two(a, size, target, t1, t2); 33 if (flag) 34 cout << t1 << " + " << t2 << " = " << target << endl; 35 else 36 cout << "can not find t1 and t2." << endl; 37 return 0; 38 }
IT公司100题-14-排序数组中和为给定值的两个数字,布布扣,bubuko.com
原文:http://www.cnblogs.com/dracohan/p/3903283.html