Leetcode 308. Range Sum Query 2D - Mutable

题目

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: The matrix is only modifiable by the update function. You may assume the number of calls to update and sumRegion function is distributed evenly. You may assume that row1 ≤ row2 and col1 ≤ col2.

思路

这道题是2d mutable subarray sum query问题,尽管只使用prefix sum array还是不够efficient,但是已经足够优秀了。这里我们使用的技巧叫做row prefix sum array。尽管我们现在query的对象是一个matrix,但是使用row prefix sum array的结果就是add operation is O(col), sum operation is O(row)

复杂度

space O(mn), time add O(col), time sum O(row)

代码

  public class NumMatrix {

    int[][] matrix;
    int[][] rowSum;

    public NumMatrix(int[][] matrix) {
        // check edge case
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return;
        }
        // preprocess
        this.matrix = matrix;
        int row = matrix.length;
        int col = matrix[0].length;
        this.rowSum = new int[row][col];

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (j == 0) {
                    rowSum[i][j] = matrix[i][j];
                } else {
                    rowSum[i][j] = rowSum[i][j - 1] + matrix[i][j];
                }
            }
        }
    }

    public void update(int row, int col, int val) {
        int diff = val - matrix[row][col];
        matrix[row][col] = val;

        for (int j = col; j < rowSum[row].length; j++) {
            rowSum[row][j] += diff;
        }
    }

    public int sumRegion(int row1, int col1, int row2, int col2) {
        int result = 0;

        for (int i = row1; i <= row2; i++) {
            int shortSum = col1 == 0? 0: rowSum[i][col1 - 1];
            int longSum = rowSum[i][col2];

            result += (longSum - shortSum);
        }
        return result;
    }
}


// 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);

results matching ""

    No results matching ""