AcWing 800. 数组元素的目标和 Java
原题链接
简单
作者:
leo_0
,
2020-06-21 14:42:36
,
所有人可见
,
阅读 570
题目描述
算法1
(双指针) $O(n+m)$
Java 代码
import java.util.*;
public class Main {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int x = sc.nextInt();
int[] a = new int[n];
int[] b = new int[m];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
for (int i = 0; i < m; i++) {
b[i] = sc.nextInt();
}
int[] res = sum(a, b, x);
System.out.println(res[0]+" "+res[1]);
}
private static int[] sum(int[] a, int[] b, int x){
int j = b.length-1;
int len1 = a.length;
int len2 = b.length;
for(int i = 0;i<len1;i++){
while(j>=0 && a[i]+b[j]>x){
j--;
}
if((a[i]+b[j]) == x){
return new int[]{i, j};
}
}
return new int[2];
}
}