猿问

2d 数组 JAVA 中指定维度的最大子数组

我试图找到子数组左上角的索引,其总和最大。我见过找到最大子数组的算法,但这些算法不适合我的需求,因为我需要在使用算法之前设置子数组的维度。


/**

 * Finds the rectangle of height h and width w within the band

 * row0 <= row < row0 + h with the most "ink" in it, or the largest sum in it

 * @param int[][] image - A 2d array of light intensity values of each pixel in an image

 * @param h, w - Dimensions of the specified rectangle with height h and width w

 * @param row0 - the index of where it should start constructing rectangles? (I'm not sure)

 * @return The index of the leftmost column of the rectangle

 */

private int findHorzPosition(int[][] image, int row0, int h, int w) {

int maxSum = 0;

int maxRow = 0;

    for(int p = row0; p <= image.length - 1; p++) {

        int[][] tempArr = new int[image.length - row0][image[p].length - 1];

        for(int q = 0; q <= image[p].length - 1; q++) {

            tempArr[p][q] = image[p][q];


            for(int i = 0; i <= tempArr.length - 1; i++) {

                int rowSum = 0;

                for(int j = 0; j <= tempArr[i].length - 1; j++) {

                    rowSum += image[i][j];

                }


                if (rowSum > maxSum) {

                    maxSum = rowSum;

                    maxRow = i;

                }

            }

        }

    }

    return maxRow;

}

这是我拥有的,但我似乎无法让它工作。对我能做些什么有什么建议吗?


千万里不及你
浏览 113回答 1
1回答

蓝山帝景

该方法的javadoc说:findHorzPosition查找带子中具有最多“墨水”或最大总和的带子内的高度和宽度的矩形hwrow0 <= row < row0 + h这意味着波段很高,即该方法应搜索具有行中顶行的矩形。因此,代码不应具有&nbsp;p1&nbsp;循环。hrow0javadoc还说:@return矩形最左侧列的索引代码返回 。对于总和最大的矩形,代码应返回&nbsp;q1&nbsp;的值,而不是为总和最大的行返回 的值。maxRowi1)变量名称毫无意义,使得代码难以理解。具有单字符名称的局部变量应仅在含义明显时使用,例如&nbsp;i,&nbsp;j, ...表示索引,或&nbsp;x、y、z&nbsp;表示坐标。在你的代码中,p、q、i&nbsp;和&nbsp;j&nbsp;不是明显的名称。将&nbsp;q&nbsp;重命名为左侧,将 i&nbsp;重命名为行,将&nbsp;j&nbsp;重命名为&nbsp;col。
随时随地看视频慕课网APP

相关分类

Java
我要回答