思想:
两个有序的数组,i 指针从a 数组的头开始遍历,j 指针从b 数组的尾开始遍历,这样可以保证两个数组至多遍历一遍,时间复杂度为O(n)
代码如下:
package cn.liyi.day07;
import java.util.Scanner;
public class Demo800 {
public static int N = 10010;
public static int[] a = new int[N];
public static int[] b = new int[N];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int x = sc.nextInt();
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
for (int i = 0; i < m; i++) {
b[i] = sc.nextInt();
}
for(int i = 0, j = m - 1; i < n; i ++) {
while(j >= 0 && a[i] + b[j] > x){
j --;
}
if(a[i] + b[j] == x){
System.out.println(i + " " + j);
break;
}
}
System.out.println("无!");
}
}