我需要检查 [5][5]
的两个二维数组是否包含相同的值,即使其中一个被打乱也是如此。
如果两个数组包含相同的值,即使它们以不同的方式排列,我也需要返回 true 的方法,例如:
- 1,2,3,4,5
- 6,7,8,9,10
- 11,12,13,14,15
- 16,17,18,19,20
- 21,22,23,24,25
和:
- 25,24,23,22,21
- 1,2,3,4,5,
- 7,8,9,10,6
- 20,19,18,17,16
- 15,14,13,12,11
当两者具有相同的值时返回 true 的最佳方法是什么?
最佳答案
这是我的解决方案。使用起来相当简单。
int[][] array1 = {
{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15},
{16,17,18,19,20},
{21,22,23,24,25}
};
int[][] array2 = {
{25,24,23,22,21},
{1,2,3,4,5},
{7,8,9,10,6},
{20,19,18,17,16},
{15,14,13,12,11}
};
sort2D(array1);
sort2D(array2);
System.out.println(Arrays.deepEquals(array1, array2));
在这种情况下打印 true
。
方法sort2D
实现如下:
public static void sort2D(int[][] array) {
for (int[] arr : array) {
Arrays.sort(arr);
}
Arrays.sort(array, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return new BigInteger(Arrays.toString(o1).replaceAll("[\\[\\], ]", ""))
.compareTo(new BigInteger(Arrays.toString(o2).replaceAll("[\\[\\], ]", "")));
}
});
}
您可以通过预编译正则表达式来进一步优化它,但基本上,您应该明白了。
关于Java,如何检查两个二维数组是否包含相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10972938/