解决Java中以下问题的最佳方法是什么?
有3个二维数组,它们的行和列数相等:
Array1:
[1]: {1, 2, 3}
[2]: {2, 2, 4}
[3]: {1, 1, 1}
Array2:
[1]: {1, 2, 0}
[2]: {1, 2, 3}
[3]: {1, 0, 1}
Array3:
[1]: {1, 1, 1}
[2]: {1, 2, 3}
[3]: {1, 0, 1}
我需要找出所有数组中存在的行的索引.在以上示例中,答案应为:[1],[2],[2]
阵列1
[1]:{1、2、3}
数组2:
[2]:{1、2、3}
数组3:
[2]:{1、2、3}
更新:有内置函数可以执行此操作吗?还是FOR循环是唯一的解决方案?
最佳答案
我将执行以下操作:
>创建一个在数组中占一行并实现哈希码和等于的类.
>将前两个数组中的每一行(包装在上面的类中)插入两个HashMaps中
>对于最后一个数组中的每一行,确定它们是否存在于HashMaps中
编辑#2,意识到映射将需要颠倒.
private Map<MyClass, Integer> map(int[] array){
Map<MyClass, Integer> arrayMap = new HashMap<>();
for (int i; i<array.length; i++)
arrayMap.put(new MyClass(array[i]), i);
}
private mySearch(){
int[] array1, array2, array3;
Map<MyClass, Integer> map1 = map(array1);
Map<MyClass, Integer> map2 = map(array2);
for (int i=0; i<array3.lenght; i++){
MyClass row = new MyClass(array3[i]);
Integer array1Row = map1.get(row);
Integer array2Row = map2.get(row);
if (array1Row != null && array2Row != null){
// Matching rows found
}
}
}