#include<bits/stdc++.h>
using namespace std;
const int N = 100003;
int a[N], b[N];
int main() {
int n, m, x;
cin >> n >> m >> x;
for (int i = 0; i < n; i++)
cin >> a[i];
for (int i = 0; i < m; i++)
cin >> b[i];
for (int i = 0, j = m-1; i < n; i++) {
while (j >=0 && a[i] + b[j] > x)
j--;
//b从大到小遍历
if (j >= 0 && a[i] + b[j] == x) {
cout << i << " " << j;
return 0;
}
}
下面是我将b从小到大遍历的代码,只是改动了遍历方向,且测试之后发现不会溢出,可以取到尾值,但为什么不AC呢,请大家帮忙答疑。
#include<bits/stdc++.h>
using namespace std;
const int N = 100003;
int a[N], b[N];
int main() {
int n, m, x;
cin >> n >> m >> x;
for (int i = 0; i < n; i++)
cin >> a[i];
for (int i = 0; i < m; i++)
cin >> b[i];
//b从小到大遍历
for (int i = 0, j = 0; i < n; i++) {
while (j < m && a[i] + b[j] < x)
j++;
if (j < m && a[i] + b[j] == x) {
cout << i << " " << j;
return 0;
}
j--;
}
}
【以下回答由 GPT 生成】
在代码的第二段中,将b数组的遍历顺序改为从小到大时出现问题的原因是在while循环的条件中使用了错误的判断,应该是a[i] + b[j] > x
,而不是a[i] + b[j] < x
。这个错误导致了循环的终止条件不正确,从而导致结果不准确。
以下是正确的代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 100003;
int a[N], b[N];
int main() {
int n, m, x;
cin >> n >> m >> x;
for (int i = 0; i < n; i++)
cin >> a[i];
for (int i = 0; i < m; i++)
cin >> b[i];
// b从小到大遍历
for (int i = 0, j = 0; i < n; i++) {
while (j < m && a[i] + b[j] > x)
j++;
if (j < m && a[i] + b[j] == x) {
cout << i << " " << j;
return 0;
}
j--;
}
}
这样修改后,代码就能够正确地找到数组元素之和等于目标值的索引位置了。
【相关推荐】