Java 在两个数组中查找匹配数
嘿,我正在尝试编写一个方法来比较两个数组,并返回它们共有的值的数量 例如,如果有两个阵列:Java 在两个数组中查找匹配数,java,arrays,oop,Java,Arrays,Oop,嘿,我正在尝试编写一个方法来比较两个数组,并返回它们共有的值的数量 例如,如果有两个阵列: arr{0,4,2,5} arr1{0,7,4,4} 然后该方法将返回2 这就是我到目前为止所做的: public int numDigitsCorrect(Permutation other) { int c=0; for(int i=0; i<nums.length; i++) { for(int x=0; x<nums.length;x++) {
arr{0,4,2,5}
arr1{0,7,4,4}
然后该方法将返回2
这就是我到目前为止所做的:
public int numDigitsCorrect(Permutation other) {
int c=0;
for(int i=0; i<nums.length; i++) {
for(int x=0; x<nums.length;x++) {
if(nums[i]==other.nums[x]) {
System.out.println(nums[i] + " " + other.nums[x] + " ");
c++;
}
}
}
return c;
}
public int numDigitsCorrect(置换其他){
int c=0;
对于(inti=0;i,如果您使用,它将更加清晰易读。这也将降低代码的复杂性
比如:
您需要更改当前功能,如下所述:
public int numDigitsCorrect(Permutation other)
{
int c=0;
for(int i=0; i<nums.length; i++) {
for(int x=0; x<other.length;x++) {
if(nums[i]==other[x]) {
System.out.println(nums[i] + " " + other[x] + " ");
c++;
}
}
}
return c;
}
你运行代码了吗?你得到了什么错误?在第二个循环中,现在输出的xAs是3。在c++;
之后添加break;
,这将在第二个数组中停止4次计数,那么输出将变为2。你可以引入Set
来提高代码的复杂度。@Niroshan,如果我们反转输入,那么再加一次。@Niroshann输出将为3。
2
2
4
3
public int numDigitsCorrect(Permutation other)
{
int c=0;
for(int i=0; i<nums.length; i++) {
for(int x=0; x<other.length;x++) {
if(nums[i]==other[x]) {
System.out.println(nums[i] + " " + other[x] + " ");
c++;
}
}
}
return c;
}
int[] nums = {0,4,2,5};
int[] other = {0,7,4,4};