题目链接
法一(二维前缀和)
public class Solution304 {
private int[][] presum;
public Solution304(int[][] matrix) {
int rowSize = matrix.length, colSize = matrix[0].length;
this.presum = new int[rowSize + 1][colSize + 1];
for (int row = 0; row < rowSize; row++) {
for (int col = 0; col < colSize; col++) {
presum[row + 1][col + 1] = presum[row + 1][col] + presum[row][col + 1] - presum[row][col] + matrix[row][col];
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
return presum[row2 + 1][col2 + 1] - presum[row2 + 1][col1] - presum[row1][col2 + 1] + presum[row1][col1];
}
}
本地测试
lay.showTitle(304);
int[][] matrix304 = new int[][]{{3, 0, 1, 4, 2}, {5, 6, 3, 2, 1}, {1, 2, 0, 1, 5}, {4, 1, 0, 1, 7}, {1, 0, 3, 0, 5}};
arrayOpt.showIntTwoDimArray(matrix304, matrix304.length);
Solution304 sol304 = new Solution304(matrix304);
System.out.println(sol304.sumRegion(2, 1, 4, 3));
System.out.println(sol304.sumRegion(1, 1, 2, 2));
System.out.println(sol304.sumRegion(1, 2, 2, 4));