IT公司100题-14-排序数组中和为给定值的两个数字

时间:2023-03-09 02:52:27
IT公司100题-14-排序数组中和为给定值的两个数字

问题描述:

输入一个升序排序的数组,给定一个目标值target,求数组的两个数a和b,a+b=target。如果有多个组合满足这个条件,输出任意一对即可。
例如,输入升序数组【1, 3, 4, 5, 13, 17】和目标值20。输出3和17。
分析:
最简单的办法,直接遍历,时间复杂度为O(n^2)。
双下标法:low和high
a[low]+a[high] < target, low++;
a[low]+a[high] > target, high–;
a[low]+a[high] == target, return low and high;
代码实现如下所示:
 // 14.cc
#include
using namespace std; bool find_two(int* a, size_t size, int target, int& t1, int& t2) {
bool flag = false;
if (size < )
return flag; size_t low = ;
size_t high = size - ; while (low < high) { int s = a[low] + a[high]; if (s > target)
high--;
else if (s < target)
low++;
else {
t1 = a[low];
t2 = a[high];
flag = true;
return flag;
}
}
return flag;
} int main() {
int a[] = {, , , , , };
int size = sizeof(a) / sizeof(int);
int target = ;
int t1, t2;
bool flag = find_two(a, size, target, t1, t2);
if (flag)
cout << t1 << " + " << t2 << " = " << target << endl;
else
cout << "can not find t1 and t2." << endl;
return ;
}