LeetCode 304. Range Sum Query 2D - Immutable

链接:https://leetcode.com/problems/range-sum-query-2d-immutable/

思路

矩阵值不变,可以缓存部分和,以减少计算
Approach 1: Caching rows. cach[r][c]表示matrix[r][0]~matrix[r][c]总和
Approach 2: Caching matrix. cach[r][c]表示matrix[0][0]~matrix[r][c]总和

代码

// Approach 1
class NumMatrix {
private:
    vector<vector<int>> cach;
public:
    NumMatrix(vector<vector<int>>& matrix) {
        int n = matrix.size();
        if(!n) return;
        int m = matrix[0].size();    
        cach = {n, vector<int>(m)};
        for(int r = 0; r < n; r++) {
            int prev = 0;
            for(int c = 0; c < m; c++) {
                prev += matrix[r][c];
                cach[r][c] = prev;
            }
        }   
    }
    
    int sumRegion(int row1, int col1, int row2, int col2) {
        int sum = 0;
        for(int r = row1; r <= row2; r++) {
            sum += cach[r][col2] - (col1 == 0 ? 0 : cach[r][col1-1]);
        }
        return sum;
    }
};

/**
 * Your NumMatrix object will be instantiated and called as such:
 * NumMatrix* obj = new NumMatrix(matrix);
 * int param_1 = obj->sumRegion(row1,col1,row2,col2);
 */
// Approach 2
class NumMatrix {
private:
    vector<vector<int>> cach;
public:
    NumMatrix(vector<vector<int>>& matrix) {
        int n = matrix.size();
        if(!n) return;
        int m = matrix[0].size();    
        cach = {n, vector<int>(m)};
        int prev = 0;
        for(int r = 0; r < n; r++) {
            for(int c = 0; c < m; c++) {
                prev += matrix[r][c];
                cach[r][c] = prev;
            }
        }   
    }
    
    int sumRegion(int row1, int col1, int row2, int col2) {
        int top = row1 == 0 ? 0 : cach[row1-1][col2],
            left = col1 == 0 ? 0 : cach[row1][col1-1],
            top_left = (row1 == 0 || col1 == 0) ? 0 : cach[row1-1][col1-1];
        return cach[row2][col2] - top - left + top_left;
    }
};

/**
 * Your NumMatrix object will be instantiated and called as such:
 * NumMatrix* obj = new NumMatrix(matrix);
 * int param_1 = obj->sumRegion(row1,col1,row2,col2);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值