304. Range Sum Query 2D - Immutable

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.
  • 這道題目本身比較簡單,不過稍微略顯繁瑣。對於其中的部分細節問題要特殊處理。
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);
 */
發佈了102 篇原創文章 · 獲贊 19 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章