LeetCode 308. Range Sum Query 2D - Mutable(二维区间求和)

原题网址:https://leetcode.com/problems/range-sum-query-2d-mutable/

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).

Range Sum Query 2D
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.

Example:

Given matrix = [
  [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) -> 8
update(3, 2, 2)
sumRegion(2, 1, 4, 3) -> 10

Note:

  1. The matrix is only modifiable by the update function.
  2. You may assume the number of calls to update and sumRegion function is distributed evenly.
  3. You may assume that row1 ≤ row2 and col1 ≤ col2.

方法:类似一维的情况,使用树状数组。

public class NumMatrix {
    private int[][] sums;
    private int[][] matrix;

    public NumMatrix(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return;
        this.sums = new int[matrix.length+1][matrix[0].length+1];
        this.matrix = new int[matrix.length][matrix[0].length];
        for(int i=0; i0) {
            int j=col;
            while (j>0) {
                sum += sums[i][j];
                j -= (j & -j);
            }
            i -= (i & -i);
        }
        return sum;
    }

    public int sumRegion(int row1, int col1, int row2, int col2) {
        if (matrix == null) return 0;
        return sum(row2,col2) - sum(row2, col1-1) - sum(row1-1, col2) + sum(row1-1, col1-1);
    }
}


// Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix = new NumMatrix(matrix);
// numMatrix.sumRegion(0, 1, 2, 3);
// numMatrix.update(1, 1, 10);
// numMatrix.sumRegion(1, 2, 3, 4);

你可能感兴趣的:(区间,求和,二维数组,树状数组,矩阵)