AcWing 800. 数组元素的目标和
原题链接
简单
作者:
Broken_
,
2024-09-25 17:08:18
,
所有人可见
,
阅读 1
java 代码
import java.io.BufferedInputStream;
import java.util.Scanner;
/**
* 求满足 a[i] + b[j] = x 的(i,j)数对
*/
public class Main {
private static final int N = 100000;
private static int[] a = new int[N];
private static int[] b = new int[N];
public static void main(String[] args) {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
int n = sc.nextInt(); // a数组长度
int m = sc.nextInt(); // b数组长度
int x = sc.nextInt(); // 目标值
// 检查数组长度
if (n > N || m > N) {
throw new IllegalArgumentException("数组长度超出最大限制!");
}
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
for (int i = 0; i < m; i++) b[i] = sc.nextInt();
int left = 0, right = m - 1;
String result = " ";
while (left < n && right >= 0) {
int sum = a[left] + b[right];
if (sum == x) {
result = left + " " + right;
break; // 找到唯一解后退出循环
} else if (sum < x) {
left++;
} else {
right--;
}
}
// 输出结果
System.out.println(result);
}
}