java - 二维数组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;
}
这就是我所拥有的,但我似乎无法让它工作。关于我能做什么的任何建议?
解决方案
该findHorzPosition
方法的javadoc说:
查找带内“墨水”最多或总和最大的带的高度
h
和宽度矩形w
row0 <= row < row0 + h
这意味着乐队h
很高,即该方法应该搜索一个在 row 中具有顶行的矩形row0
。
因此,代码不应有p
1 循环。
javadoc还说:
@return
矩形最左列的索引
代码正在返回maxRow
。代码应该为总和最大的矩形返回值q
1,而不是总和最大的行的值。i
1) 变量名无意义,使代码难以理解。仅当含义很明显时才应使用具有单字符名称的局部变量,例如i
,j
用于索引的 , , ... 或x
用于y
坐标z
的 , 。在您的代码中,p
、q
、i
和j
不是显而易见的名称。重命名q
为left
、和。i
_row
j
col
推荐阅读
- javascript - 在变量中使用 html
- tensorflow - 具有分布在多个 GPU 上的 TFRecords 数据集的 Keras 模型
- kubernetes - 我想知道可用于 Kubernetes Google Cloud Shell 的最简单的目录服务
- python - 协调全局和虚拟 uWSGI 安装
- meshlab - Meshlab 顶点属性“vsel”缺失
- thrift - Envoy + Istio 的节俭率限制
- java - APACHE POI 4.1:从十六进制代码设置单元格背景颜色
- excel - 如果单元格包含值,如何在下面插入一行
- mapbox - Mapbox 仅具有几何特征
- laravel - 如何在 Laravel 中同时将 Slug 用于类别、帖子和页面