問題描述:
比較兩個數組,要求從數組最後一個元素開始逐個元素向前比較,如果2個數組長度不等,則只比較較短長度數組個數元素。請編程實現上述比較,並返回比較中發現的相等元素的個數。
代碼:
package com.test.test;
public class Test {
public static void main(String[] args) {
int []a = {23,43,1,32,4,54,10,11,};
int []b = {43,3,32,3,4,10,11};
int alength = a.length;
int blength = b.length;
int count = 0;
if (alength<=blength){
for (int i = blength-1;i>(blength-alength-1) ; i--) {
if(a[i-(blength-alength)]==b[i]){
count++;
System.out.println("相同的元素爲"+b[i]);
}
}
}else{
for (int j = alength-1; j > (alength-blength-1); j--) {
if(a[j]==b[j-(alength-blength)]){
count++;
System.out.println("相同的元素爲"+a[j]);
}
}
}
System.out.println("相同的元素有"+count+"個");
}
}