方法:前缀和
初始化时对矩阵的每一行计算前缀和,检索时对二维区域中的每一行计算子数组和,然后对每一行的子数组和计算总和。
package com.algo.lesson01;
public class Solution_LCR013 {
/*private int[][] matrix;
private int[][] sums;
public Solution_LCR013(int[][] matrix) {
int rows = matrix.length;
int columns = matrix[0].length;
this.matrix = new int[rows][columns];
for (int i = 0; i < rows; i++) {
this.matrix[i] = Arrays.copyOf(matrix[i],columns);
}
this.sums = new int[rows+1][columns+1];
//this.sums[i][j] 表示前i行前j列中间的和
for (int i = 1; i <= rows ; i++) {
for (int j = 1; j <= columns ; j++) {
this.sums[i][j] = this.sums[i-1][j]+this.sums[i][j-1]-this.sums[i-1][j-1]+this.matrix[i-1][j-1];
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
int sum = 0;
for (int i = row1; i <= row2; i++) {
for (int j = col1; j <= col2 ; j++) {
sum += this.matrix[i][j];
}
}
return sum;
}*/
private int[][] sums;
public Solution_LCR013(int[][] matrix) {
int m = matrix.length;
if (m>0){
int n = matrix[0].length;
sums = new int[m][n+1];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
sums[i][j+1] = sums[i][j] + matrix[i][j];
}
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
int sum = 0;
for (int i = row1; i <= row2; i++) {
sum += sums[i][col2 + 1] - sums[i][col1];
}
return sum;
}
}