【问题标题】:Delete column and row of 2d Array after every iteration每次迭代后删除二维数组的列和行
【发布时间】:2017-10-13 07:34:37
【问题描述】:

在一个项目中,我需要计算给定分数的最大值。之后,应删除此特定行和相关列,以便在每一行中仅获得一个最大值。所以我的结果应该是这样的:

结果

这是我目前所拥有的。

    float max = Float.MIN_VALUE;
    int remove_row = firstCluster.size()+1;
    int remove_column = firstCluster.size()+1;
    float[ ][ ] scores = new float[firstCluster.size()][secondCluster.size()];

    for(int i=0; i<scores.length; i++){
       if ( i == remove_row)
            continue;

        for(int j=0; j<scores[i].length; j++){
            if ( j == remove_column){
                continue;
            }
            else{
                System.out.print(scores[i][j]);
                if(scores[i][j] >= max)
                {
                    max = Math.max(max, scores[i][j]);
                    remove_row = i;
                    remove_column = j;
                    System.out.print("Max: "+max);
                }
            }
        }
        System.out.println("##############################");
    }

这个想法是跳过前一个最大值的列和行,但如果你在 3 次迭代中,那么你只是跳过前一个的列和行,而不是所有以前的迭代。有没有更好的方法来解决这个问题?我不需要使用必要的二维数组

【问题讨论】:

  • 如果所有值都是正数,只需将“删除”的行或列的值设置为零,这样就不会影响下一次迭代。
  • 我同意@TDG - 循环原始二维数组,不要在每次迭代后构建一个新数组。不要在单元格中添加零,而是维护两个 Set - usedRowsusedColumns - 跟踪您已划掉的行和列,并在 if(scores[i][j] &gt;= max) 之前使用额外的 if 语句发送这些>
  • 很高兴用易于理解的图像解释问题,顺便说一句!
  • @Stefan 您的解决方案非常好,行和列都被适当地运送了。如果在最后一次迭代中零只是左值,我只有问题。在这种情况下,不会计算最后一个最大值
  • @Stefan Thnx!它就像一个魅力!

标签: java arrays arraylist multidimensional-array


【解决方案1】:

只是总结 cmets 来建立一个正确的答案:

不要在单元格中输入零,而是维护两个 Set - usedRowsusedColumns - 跟踪您已划掉的行和列,并在 if(scores[i][j] &gt;= max) 之前使用额外的 if 语句发送这些行和列

记得在每次迭代开始时重置最大值:

max = Float.MIN_VALUE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 2020-10-06
    • 2013-09-15
    • 2012-03-17
    • 2014-03-27
    • 2020-09-06
    • 2012-01-23
    相关资源
    最近更新 更多