我有一个二维数组,其中包含不同长度的行。我想编写一个方法,该方法返回一个由列的最大元素组成的新数组。如果这是一个简单的n x m数组,那会很容易,但是由于行的长度是可变的,因此我无法提出解决方案以解决列中元素的不同数量。

例如,数组如下所示:

int[][] test = { { 0, 1, 4, 5, 6, 8 },
                 { 4, 5, 8, 3, 9 },
                 { 3, 6, 2 }
               };

预期结果将是:
int[] result =  {4, 6, 8, 5, 9, 8};

我有找到行的最大元素的代码,但是我不知道如何针对列进行调整。
int[] result = new int[m.length];

      for (int x = 0; x < m.length; x++) {
         result[x] = 0;
         for (int y = 0; y < m[x].length; y++) {
            if (result[x] < m[x][y]) {
               result[x] = m[x][y];
            }
         }
      }

任何帮助,将不胜感激

编辑:我现在意识到,要做的第一件事就是查找具有最大元素数的行,因为它定义了新数组的大小。从那里开始..应该将一行元素与新数组中相同位置的元素进行比较。并做到每一行。那么其他行有多短都没关系。我走对了吗?

最佳答案

首先,您要查找最大行的长度。

然后,类似于您的算法,但是您要确保不要超出范围例外。而已:

int maxcol = 0;
for(int i = 0; i < test.length; i++)
    if(test[i].length > maxcol)
        maxcol = test[i].length;


int[] result = new int[maxcol];

for (int j = 0; j < maxcol; j++)
    for (int i = 0; i < test.length; i++)
        if (test[i].length > j && result[j] < test[i][j])
            result[j] = test[i][j];

09-26 20:52
查看更多