Java 比较两个数组。返回值错误(1)
我创建了这个方法,比较两个数组的数字,然后返回多少个数字彼此相等,但无论多少个数字相等,该方法每次都返回值1。 (两个数组的长度相同)Java 比较两个数组。返回值错误(1),java,arrays,methods,return,main,Java,Arrays,Methods,Return,Main,我创建了这个方法,比较两个数组的数字,然后返回多少个数字彼此相等,但无论多少个数字相等,该方法每次都返回值1。 (两个数组的长度相同) publicstaticvoidmain(字符串[]args){ inta[]={1,4,6,7,8,10,13}; int b[]={1,2,3,4,5,6,7}; 相等(a,b); } 公共静态int-equal(int[]a,int[]b){ int j=0; for(int i=0;i
publicstaticvoidmain(字符串[]args){
inta[]={1,4,6,7,8,10,13};
int b[]={1,2,3,4,5,6,7};
相等(a,b);
}
公共静态int-equal(int[]a,int[]b){
int j=0;
for(int i=0;i
您的代码正在查找同一索引中相等的数字
有几种方法可以确定交叉口的大小
一个简单但O(m*n)的实现是为A的每个元素迭代b的所有元素
如果对数组进行了排序,您可以对两个数组使用单独的索引,在无法再匹配时向前推进。这将是O(m+n)。(如果它们没有排序,您可以先对它们进行排序,代价是O(m logm+n logn)
如果每个数组没有重复的成员,另一种方法是根据集合差的大小来计算交集的大小。例如at。关键部分是将每个数组转换为一个集合,并通过从一个集合中删除另一个集合来确定共有多少成员
int aSizeBefore = setA.size();
setA.removeAll( setB );
int aSizeAfter = setA.size();
return aSizeBefore - aSizeAfter;
如果要检查数组
a
中的任何单个数字是否也在数组b
中,则应使用嵌套for循环
e、 g
具有相同值的元素可能位于不同的索引中。假设数组已排序,则可以按以下方式编写:
public static int equal(int[] a, int[] b) {
int count = 0;
for(int i = 0; i < a.length - 1; i++) {
for(int j = 0; i < b.length - 1; j++) {
if (a[j] < b[j]) {
// we came to the part where all elements in b are bigger
// than our selected element in a
break;
}
else if (a[j] == b[j]) {
count++;
}
}
}
System.out.println(count);
return count;
}
公共静态int-equal(int[]a,int[]b){
整数计数=0;
对于(int i=0;i
如果不能保证数组已排序,则可以删除If块,并从循环中删除else-If-else。如果要知道两个数组中都有多少个数字,并且保证它们已排序,则应尝试以下操作:
public static int equal(int[] a, int[] b) {
int j, result = 0;
int lastFound = 0;
for (int i = 0; i < a.length - 1; i++) {
for (j = lastFound; j < b.length; j++) {
if (a[i] == b[j]) {
result++;
lastFound = j;
break;
} else {
if (a[i] < b[j]) break;
}
}
}
return result;
}
公共静态int-equal(int[]a,int[]b){
int j,结果=0;
int lastFound=0;
对于(int i=0;i
使用变量
lastFound
将加快循环速度,但只有当数组按顺序排列时才有帮助,如您的示例所示。对于那些完全正确的数组。
1 == 1 // Yes, increment j
4 == 2 // Nope
6 == 3 // Nope
7 == 4 // Nope
8 == 5 // Nope
10 == 6 // Nope
13 == 7 // Nope
public static int equal(int[] a, int[] b) {
int count = 0;
for(int i = 0; i < a.length - 1; i++) {
for(int j = 0; i < b.length - 1; j++) {
if (a[j] < b[j]) {
// we came to the part where all elements in b are bigger
// than our selected element in a
break;
}
else if (a[j] == b[j]) {
count++;
}
}
}
System.out.println(count);
return count;
}
public static int equal(int[] a, int[] b) {
int j, result = 0;
int lastFound = 0;
for (int i = 0; i < a.length - 1; i++) {
for (j = lastFound; j < b.length; j++) {
if (a[i] == b[j]) {
result++;
lastFound = j;
break;
} else {
if (a[i] < b[j]) break;
}
}
}
return result;
}