【发布时间】:2018-04-05 16:22:41
【问题描述】:
假设我有一个看起来像这样的array:
{{1,3,5,7},{2,4,6,8,10,12},{2,3,5,7,11,13,17}}
我应该如何在 Java 中创建一个与这个完全相同的新数组,除了删除了一行和一列?
我可以用一个偶数大小的数组来执行这个任务,但是锯齿状的数组给我带来了一些麻烦。我考虑过先创建一个列数未指定的新数组,但我该从哪里开始呢?
/**
* Creates a new array that is a copy of the input matrix,
* except that one row and one column have been altered.
* Precondition: the row index is between 0 (inclusive)
* and the number of rows of matrix (not inclusive)
*
* @param matrix the input two dimensional array
* @param row the index of the row to remove
* @param col the index of the column to remove
*/
public static int[][] removeRowAndCol(int[][] matrix, int row, int col) {
int[][] altered = new int[(matrix.length - 1)][];
int x = 0;
for (int i = 0; i < matrix.length; i++) {
if (matrix[i].length < col + 1 && i != row) {
altered[x] = new int[matrix[i].length];
for (int j = 0; j < altered[x].length; j++) {
altered[x][j] = matrix[i][j];
}
if (x < matrix.length - 1) {
x++;
}
} else if (matrix[i].length > col && i != row) {
altered[x] = new int[matrix[i].length - 1];
int y = 0;
for (int z = 0; z < matrix[i].length - 1; z++) {
if (z != col) {
altered[x][y] = matrix[i][z];
y++;
} else {
z--;
}
}
if (x < matrix.length - 1) {
x++;
}
}
}
return altered;
}
运行测试用例时,例如:
removeRowAndCol(new int[][]{{1, 2}, {3, 4}}, 1, 1)
该方法返回正确的{{1}}。
但是,像这样:
int[][] array = {{1,2,3,4},{11,12,13,14,15,16},{21,22,23,24},{31,32,33}};
removeRowAndCol(array, 0, 0)
removeRowAndCol(array, 2, 3)
该方法将冻结。
有人可以看看代码并告诉我我做错了什么吗?
【问题讨论】:
标签: java arrays matrix multidimensional-array jagged-arrays