[Leetcode]Range Sum Query 2D - Immutable

来源:互联网 发布:python 可视化 d3.js 编辑:程序博客网 时间:2024/05/16 12:58

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) -> 8sumRegion(1, 1, 2, 2) -> 11sumRegion(1, 2, 2, 4) -> 12

Note:

  1. You may assume that the matrix does not change.
  2. There are many calls to sumRegion function.
  3. You may assume that row1 ≤ row2 and col1 ≤ col2.

class NumMatrix {private:    vector<vector<int>>hSumMatrix;//mxn    vector<vector<int>>cSumMatrix;//mxn    int m,n;    int sum;public:    NumMatrix(vector<vector<int>> &matrix) {        m = matrix.size();        n = m?matrix[0].size():0;        sum = 0;        if(m==0 || n==0)return;        for(int i = 0;i < m;i++){            hSumMatrix.push_back(vector<int>(n,0));            for(int j = 0;j < n;j++){                sum += matrix[i][j];                hSumMatrix[i][j] = matrix[i][j];                if(j > 0)hSumMatrix[i][j] += hSumMatrix[i][j-1];            }        }                for(int i = 0;i < m;i++){            cSumMatrix.push_back(vector<int>(n,0));        }        for(int j = 0;j < n;j++){            cSumMatrix[0][j] = matrix[0][j];            for(int i =1;i < m;i++){                cSumMatrix[i][j] = matrix[i][j];                if(i > 0)cSumMatrix[i][j] += cSumMatrix[i-1][j];            }        }           }    int sumRegion(int row1, int col1, int row2, int col2) {        if(m==0||n==0)return 0;        int ret = sum;                //top rows        for(int i = 0;i < row1;i++){            ret -= hSumMatrix[i][n-1];        }        //bottom        for(int i = row2+1;i < m;i++){            ret -= hSumMatrix[i][n-1];        }                //left columns        for(int j = 0;j < col1;j++){            ret -= (cSumMatrix[row2][j] - (row1?cSumMatrix[row1-1][j]:0));        }                //right colums        for(int j = col2+1;j < n;j++){            ret -=(cSumMatrix[row2][j] - (row1?cSumMatrix[row1-1][j]:0));        }                return ret;    }};// Your NumMatrix object will be instantiated and called as such:// NumMatrix numMatrix(matrix);// numMatrix.sumRegion(0, 1, 2, 3);// numMatrix.sumRegion(1, 2, 3, 4);



0 0
原创粉丝点击