[英]Remove last element of each row of a 2D array
我有一个二维数组,其中行的长度不同,我应该编写一个方法,使每行的最后一个 x(即从用户输入的)数字被删除。 例如矩阵是:
{1 2 2}
{null}
{}
{1 3 2 3 3 7}
{1 2 4 5}
当用户输入 2 它应该打印:
{1}
{null}
{}
{1 3 2 3}
{1 2}
我不知道我怎么能做到这一点。 我想如果我引入一个新数组,我必须为其分配一定的大小,例如 3 行 4 列。 我什至如何制作具有不同长行的新二维数组? 行数很容易保持不变,但列对我来说是困难的。
我试过这个,但它当然不起作用。 我得到一个IndexOutOfBoundsException
。
static int[][] cutAway(int[][] m, int cutAway) {
if (m == null) return null;
int[][] x = new int[m.length][m[0].length - cutAway];
for (int row = 0; row < x.length; row++) {
for (int col = 0; col < x[row].length; col++) {
x[row][col] = m[row][col];
}
}
return x;
}
编辑:我不允许使用这些Arrays.copyOf
的东西。 所以解决方案并没有真正帮助。
您不能在循环之前分配行,因为它们可以有不同的大小。 这应该有效:
static int[][] cutAway(int[][] array, int cutAway) {
if ((array == null) || (array.length == 0)) {
return array;
}
int[][] res = new int[array.length][];
for (int row = 0; row < array.length; row++) {
res[row] = Arrays.copyOfRange(array[row], 0, Math.max(array[row].length - cutAway, 0));
}
return res;
}
Array Index out of bound 的原因是,当您减去cutAway
时,第二行的值变为负数。 添加了一个条件来检查它是否为负数。
static int[][] cutAway(int[][] m, int cutAway) {
if (m == null) return null;
int[][] x = new int[m.length][];
for (int row = 0; row < x.length; row++) {
int size = m[row].length - cutAway;
if (size < 0)
size = 0;
x[row] = new int[size];
for (int col = 0; col < x[row].length; col++) {
x[row][col] = m[row][col];
}
}
return x;
}
int[][] arr = { { 1, 2, 2 }, null, {}, { 1, 3, 2, 3, 3, 7 },
{ 1, 2, 4, 5 } };
arr = cutAway(arr, 2);
for (int[] a : arr) {
System.out.println(Arrays.toString(a));
}
印刷
[1]
null
[]
[1, 3, 2, 3]
[1, 2]
方法
static int[][] cutAway(int[][] m, int cutAway) {
if (m == null) {
return null;
}
// create a return array with no rows assigned
int[][] x = new int[m.length][];
for (int row = 0; row < x.length; row++) {
// get the source row for this run
int[] source = m[row];
// and assign it to x in case it can't be
// shortened
x[row] = source;
// now check its condition for null and length
if (source != null && source.length > cutAway) {
int[] dest = new int[source.length - cutAway];
//looks good. Assign to x
x[row] = dest;
// now do the copy using new rows length.
for (int col = 0; col < dest.length; col++) {
dest[col] = source[col];
}
}
}
return x;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.