Skip to main content

🟡 剑指 Offer II 013. 二维子矩阵的和

LeetCode 提示

题目难度 中等

原题链接 🔗 leetcode

题解1#

class NumMatrix {
    private int[][] sum;
    public NumMatrix(int[][] matrix) {        int m = matrix.length+1, n = matrix[0].length+1;        this.sum = new int[m][n];
        for (int j=1; j<n; j+=1) {            sum[0][j] = sum[0][j-1] + matrix[0][j-1];        }
        for (int i=1; i<m; i+=1) {            for (int j=1; j<n; j+=1) {                sum[i][j] = sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1] + matrix[i-1][j-1];            }        }    }        public int sumRegion(int row1, int col1, int row2, int col2) {        return sum[row2+1][col2+1] + sum[row1][col1] - sum[row2+1][col1] - sum[row1][col2+1];    }}
/** * Your NumMatrix object will be instantiated and called as such: * NumMatrix obj = new NumMatrix(matrix); * int param_1 = obj.sumRegion(row1,col1,row2,col2); */