[LeetCode] 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.

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
sumRegion(1, 1, 2, 2) -> 11
sumRegion(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.

 

這道題讓我們求一個二維區域和的檢索,是之前那道題Range Sum Query - Immutable 區域和檢索的延伸。有了之前那道題的基礎,我們知道這道題其實也是換湯不換葯,還是要建立一個累計區域和的數組,然后根據邊界值的加減法來快速求出給定區域之和。這里我們維護一個二維數組dp,其中dp[i][j]表示累計區間(0, 0)到(i, j)這個矩形區間所有的數字之和,那么此時如果我們想要快速求出(r1, c1)到(r2, c2)的矩形區間時,只需dp[r2][c2] - dp[r2][c1 - 1] - dp[r1 - 1][c2] + dp[r1 - 1][c1 - 1]即可,下面的代碼中我們由於用了輔助列和輔助行,所以下標會有些變化,參見代碼如下:

 

class NumMatrix {
public:
    NumMatrix(vector<vector<int> > &matrix) {
        if (matrix.empty() || matrix[0].empty()) return;
        dp.resize(matrix.size() + 1, vector<int>(matrix[0].size() + 1, 0));
        for (int i = 1; i <= matrix.size(); ++i) {
            for (int j = 1; j <= matrix[0].size(); ++j) {
                dp[i][j] = dp[i][j - 1] + dp[i - 1][j] - dp[i - 1][j - 1] + matrix[i - 1][j - 1];
            }
        }
    }
    int sumRegion(int row1, int col1, int row2, int col2) {
        return dp[row2 + 1][col2 + 1] - dp[row1][col2 + 1] - dp[row2 + 1][col1] + dp[row1][col1];
    }
    
private:
    vector<vector<int> > dp;
};

 

類似題目:

Range Sum Query 2D - Mutable

Range Sum Query - Immutable

Range Sum Query - Mutable

 

LeetCode All in One 題目講解匯總(持續更新中...)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM