[LC] 304. Range Sum Query 2D - Immutable

这题做法其实就很简单了。如果说我们有一个辅助二维数组f(n, n),其中任意f(i, j)是从matrix(0, 0)到matrix(i, j)的矩阵的和

那么这一题subRegion(row1, col1, row2, col2)其实就是f(row2, col2)这个矩阵,减去f(row1, col2)这个矩阵,再减去f(row2, col1)这个矩阵,最后加上f(row1, col1)这个被重复减去了两次的矩阵就可以了。注意一下row1 = 0 或者 col1 = 0的edge case就可以了。

根据上面描述,给出代码如下:

    private int[][] _calculated;
    
    public NumMatrix(int[][] matrix) {
        if (matrix.length == 0 || matrix[0].length == 0) return;
        
        this._calculated = new int[matrix.length][matrix[0].length];
        for (int i = 0; i < matrix.length; i++) {
            int curRowSum = 0;
            for (int j = 0; j < matrix[i].length; j++) {
                curRowSum += matrix[i][j];
                this._calculated[i][j] = curRowSum;
                if (i > 0) this._calculated[i][j] += this._calculated[i - 1][j]; 
            }            
        }
    }
    
    public int sumRegion(int row1, int col1, int row2, int col2) {
        int rightTop = this._calculated[row2][col2];
        int rightBot = row1 > 0 ? this._calculated[row1 - 1][col2] : 0;
        int leftTop = col1 > 0 ? this._calculated[row2][col1 - 1] : 0;
        int leftBot = row1 > 0 && col1 > 0 ? this._calculated[row1 - 1][col1 - 1] : 0;
        return rightTop - leftTop - rightBot + leftBot;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值