文章目錄

已知两个整数数组f[]与g[],它们的元素都已经从小到大排列好,而且两个数组中的元素都各不相同。例如,f[]中有1,3,4,7,9,而g[]中有3,5,7,8,10。试编写程序算出这两个数组之间有多少组相同的元素。

就上例而言,f[2]和g[1]为3是一组;f[3]与g[2]为7是第二组

依然是利用已经排好序的这个特性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class EQCount {
public static int eqCount(int[] f, int[] g) {
int i = 0;
int j = 0;
int result = 0;
while (i < f.length && j < g.length) {
if (f[i] == g[j]) {
i++;
j++;
result++;
} else if (f[i] > g[j]) {
j++;
} else {
i++;
}
}
return result;
}
public static void main(String[] args) {
int[] f = {1, 3, 4, 7, 9};
int[] g = {3, 5, 7, 8, 10};
System.out.println(eqCount(f, g));
}
}

打赏作者

文章目錄