我们可以使用双重循环来比较两个数组中的每个元素,并将匹配项存储在另一个数组中,最后返回该数组。以下是示例代码:
public static int[] findMatches(int[] arr1, int[] arr2) {
int[] matches = new int[arr1.length]; // 储存匹配项的数组
int count = 0; // 匹配项数量
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) { // 如果找到匹配项
matches[count] = arr1[i]; // 将匹配项添加到数组中
count++; // 匹配项数量增加
break; // 跳出内层循环
}
}
}
int[] result = new int[count]; // 创建与匹配项数量相同长度的数组
for (int i = 0; i < count; i++) {
result[i] = matches[i]; // 将匹配项从储存数组中复制到结果数组中
}
return result; // 返回包含所有匹配项的数组
}