【前缀和】LeetCode 304. 二维区域和检索 - 矩阵不可变

题目链接

304. 二维区域和检索 - 矩阵不可变

思路

显然,一个矩阵的元素和可以拆分成每一行相加。

那一个矩阵的每一行不就是一个个一维数组,一维数组怎么快速求子数组的和?前缀和!

所以这道题很明显就是对输入矩阵建立一个前缀和矩阵,然后求每一行的前缀和差值便能就得子矩阵的和。

代码

class NumMatrix {
    private int[][] sumMatrix;
    private int m;
    private int n;

    public NumMatrix(int[][] matrix) {
        this.m = matrix.length;
        this.n = matrix[0].length;
        this.sumMatrix = new int[m][n + 1];

        for(int i = 0; i < m; i++){
            for(int j = 1; j <= n; j++){
                this.sumMatrix[i][j] = this.sumMatrix[i][j - 1] + matrix[i][j - 1];
            }
        }
    }

    public int sumRegion(int row1, int col1, int row2, int col2) {
        int sum = 0;
        for(int i = row1; i <= row2; i++){
            sum += this.sumMatrix[i][col2 + 1] - this.sumMatrix[i][col1];
        }

        return sum;
    }
}
posted @ 2023-04-18 10:56  Frodo1124  阅读(13)  评论(0编辑  收藏  举报