304. Range Sum Query 2D

来源:互联网 发布:淘宝运营岗位要求 编辑:程序博客网 时间:2024/06/05 06:05
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 2DThe above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.
  • 这道题目本身比较简单,不过稍微略显繁琐。对于其中的部分细节问题要特殊处理。
class NumMatrix {public:    vector<vector<int>> myMatrix;    NumMatrix(vector<vector<int>> matrix) {        int n = matrix.size();        if(n <= 0){            return;        }        int m = matrix[0].size();             if(m <= 0){            return ;        }        for(int i = 0; i < n;i++){            myMatrix.push_back(matrix[i]);        }        myMatrix[0][0] = matrix[0][0];        //intial the first colum        for(int i = 1;i < n; ++i){            myMatrix[i][0] = matrix[i][0] + myMatrix[i-1][0];        }        //initial the first row        for(int i = 1;i < m; ++i){            myMatrix[0][i] = matrix[0][i] + myMatrix[0][i-1];        }        //dp & initial the sum matrix        for(int i = 1;i < n; ++i){            for(int j = 1;j < m; ++j){                myMatrix[i][j] = matrix[i][j] + myMatrix[i-1][j] + myMatrix[i][j-1] - myMatrix[i-1][j-1];                cout<<myMatrix[i][j]<<",";            }            cout<<endl;        }        return;    }    int sumRegion(int row1, int col1, int row2, int col2) {        if(row1 < 0 || row2 < 0 ||           col1 < 0 || col2 < 0){            return 0;        }        if(myMatrix.size() <= 0 || myMatrix[0].size() <= 0){            return 0;        }        int result = myMatrix[row2][col2];        if(row1 > 0){           result -= myMatrix[row1-1][col2];         }        if(col1 > 0){           result -= myMatrix[row2][col1-1];         }        if(row1 > 0 && col1 > 0){           result += myMatrix[row1-1][col1-1];        }        return result;    }};/** * Your NumMatrix object will be instantiated and called as such: * NumMatrix obj = new NumMatrix(matrix); * int param_1 = obj.sumRegion(row1,col1,row2,col2); */
原创粉丝点击