308. Range Sum Query 2D - Mutable

Posted 我的名字叫周周

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了308. Range Sum Query 2D - Mutable相关的知识,希望对你有一定的参考价值。

/*
 * 308. Range Sum Query 2D - Mutable
 * 2016-7-3 by Mingyang
 * 继续丧心病狂的Segment Tree
 */
class NumMatrix {

    int[][] tree;
    int[][] nums;
    int m;
    int n;
    
    public NumMatrix(int[][] matrix) {
        if (matrix.length == 0 || matrix[0].length == 0) return;
        m = matrix.length;
        n = matrix[0].length;
        tree = new int[m+1][n+1];
        nums = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                update(i, j, matrix[i][j]);
            }
        }
    }

    public void update(int row, int col, int val) {
        if (m == 0 || n == 0) return;
        int delta = val - nums[row][col];
        nums[row][col] = val;
        for (int i = row + 1; i <= m; i += i & (-i)) {
            for (int j = col + 1; j <= n; j += j & (-j)) {
                tree[i][j] += delta;
            }
        }
    }

    public int sumRegion(int row1, int col1, int row2, int col2) {
        if (m == 0 || n == 0) return 0;
        return sum(row2+1, col2+1) + sum(row1, col1) - sum(row1, col2+1) - sum(row2+1, col1);
    }
    
    public int sum(int row, int col) {
        int sum = 0;
        for (int i = row; i > 0; i -= i & (-i)) {
            for (int j = col; j > 0; j -= j & (-j)) {
                sum += tree[i][j];
            }
        }
        return sum;
    }
}
// time should be O(log(m) * log(n))

 

以上是关于308. Range Sum Query 2D - Mutable的主要内容,如果未能解决你的问题,请参考以下文章

Range Sum Query 2D - Immutable

304. Range Sum Query 2D - Immutable

304. Range Sum Query 2D - Immutable

0304. Range Sum Query 2D - Immutable (M)

leetcode笔记:Range Sum Query 2D - Immutable

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