LintCode 817: Range Sum Query 2D - Mutable

  1. Range Sum Query 2D - Mutable
    中文English
    Given a 2D matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). And the elements of the matrix could be changed.

You have to implement three functions:

NumMatrix(matrix) The constructor.
sumRegion(row1, col1, row2, col2) Return the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
update(row, col, val) Update the element at (row, col) to val.
Example
Example 1:

Input:
NumMatrix(
[[3,0,1,4,2],
[5,6,3,2,1],
[1,2,0,1,5],
[4,1,0,1,7],
[1,0,3,0,5]]
)
sumRegion(2,1,4,3)
update(3,2,2)
sumRegion(2,1,4,3)
Output:
8
10
Example 2:

Input:
NumMatrix([[1]])
sumRegion(0, 0, 0, 0)
update(0, 0, -1)
sumRegion(0, 0, 0, 0)
Output:
1
-1
Notice
The matrix is only modifiable by update.
You may assume the number of calls to update and sumRegion function is distributed evenly.
You may assume that row1 ≤ row2 and col1 ≤ col2.

解法1:树状数组2D版
代码如下:

class NumMatrix {
public:
    NumMatrix(vector<vector<int>> matrix) {
        nRow = matrix.size();
        nCol = matrix[0].size();
        A = matrix;
        C.resize(nRow + 1, vector<int>(nCol + 1, 0));
        for (int i = 0; i < nRow; ++i) {
            for (int j = 0; j < nCol; ++j) {
                add(i, j, A[i][j]);
            }
        }
    }
    
    void update(int row, int col, int val) {
        add(row, col, val - A[row][col]);
        A[row][col] = val;
    }
    
    int sumRegion(int row1, int col1, int row2, int col2) {
        return sum(row2, col2) - sum(row1 - 1, col2) - sum(row2, col1 - 1) + sum(row1 - 1, col1 - 1);
    }
    
private:
    vector<vector<int>> C, A;
    int nRow, nCol;
    
    int lowbit(int x) {
        return x & -x;
    }
    
    int sum(int x, int y) {
        int result = 0;
        x++; y++;
        for (int i = x; i > 0; i -= lowbit(i)) {
            for (int j = y; j > 0; j -= lowbit(j)) {
                result += C[i][j];
            }
        }
        return result;
    }
    
    void add(int x, int y, int val) {
        x++; y++;
        //int delta = val - A[x][y];
        for (int i = x; i <= nRow; i += lowbit(i)) {
            for (int j = y; j <= nCol; j += lowbit(j)) {
                C[i][j] += val;
            }
        }
    }
};

/**
 * Your NumMatrix object will be instantiated and called as such:
 * NumMatrix obj = new NumMatrix(matrix);
 * obj.update(row,col,val);
 * int param_2 = obj.sumRegion(row1,col1,row2,col2);
 */

解法2:线段树
TBD

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值