题目描述
已知两个整数数组f[]和g[],它们的元素都已经从小到大排列。例如f[]中可能有 1,2,2,3,3,g[]中有1,2,2,2,3。 请写一个程序,算出这两个数组彼此之间有多少组相同的数据。就以上例而言: f[0] 于g[0]是第一组; f[1]于g[1]是第二组; f[2]于g[2]是第三组; f[3]于g[4]是第四组。
输入
第一行为两个整数m, n(1≤m, n≤1000),分别代表数组f[], g[]的长度。 第二行有m个元素,为数组f[]。 第三行有n个元素,为数组g[]。
输出
输出等值数目。
样例输入
5 5 1 2 2 2 3 1 2 2 3 3
样例输出
4
【AC代码】
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
int f[] = new int[m];
int g[] = new int[n];
for (int i = 0; i < m; i++)
f[i] = sc.nextInt();
for (int i = 0; i < n; i++)
g[i] = sc.nextInt();
int s = 0;
if (m < n)
s = n;
else
s = m;
int sum = 0, s1 = 0, s2 = 0;
while (s1 < s && s2 < s) {
if (f[s1] > g[s2]) {
if (s2 < n - 1)
s2++;
else
break;
} else if (f[s1] < g[s2]) {
if (s1 < m - 1)
s1++;
else
break;
} else {
s1++;
s2++;
sum++;
}
}
System.out.print(sum);
}
}