发现在可变长度行java的二维数组列的最大元素 [英] finding maximum elements of columns in java 2D array of variable row length

查看:137
本文介绍了发现在可变长度行java的二维数组列的最大元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有具有不同长度的行的2维阵列。我想写一个返回新数组其中包括列的最大元素的方法。如果这是一个简单的n×m的阵列,它会很容易,但由于行是变长的,我不能拿出一个解决方案来处理不同的数列中的元素的。

I have a 2-dimensional array which has rows of different lengths. I want to write a method that returns a new array which consists of the maximum elements of columns. If this was a simple n x m array, it would be easy but since the rows are variable length, I can't come up with a solution to account for the different number of elements in columns.

例如,数组是这样的:

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

预期的结果随后将是:

The expected result would then be:

int[] result =  {4, 6, 8, 5, 9, 8};

我已经得到了code找到行的最大因素,但我的想法如何调整它的列。

I have got the code to find the maximum elements of rows but I'm out of ideas how to adjust it for the columns.

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];
            } 
         } 
      } 

任何帮助将AP preciated

Any help would be appreciated

编辑:我现在意识到,首先要做的是找到的元素的最大数量的行自定义新数组的大小。从那里..或许应该采取的行中的元素,并将其与在新阵列在相同的位置中的元素进行比较。并与每一行做到这一点。然后,它无关紧要其他行多短的。我是在正确的道路?

I realized now that the first thing to do is finding the row with maximum number of elements since that defines the size of the new array. From there.. should probably take the elements of a row and compare them with the elements at the same position in the new array. And do this with every row. Then it doesn't matter how short the other rows are. Am I on the right way?

推荐答案

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

First you want to find the length of the largest row.

然后,你的算法类似,但是你要确保不要让出界异常。就是这样:

Then, similarly to your algorithm, but you want to make sure not to get out of bounds exception. That's it:

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];

这篇关于发现在可变长度行java的二维数组列的最大元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆