leetcode 304: Range Sum Query 2D

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.

思路:

预先计算(0,0)到(i,j)所构成的矩阵的和,后续计算时直接利用该中间结果简单计算即可;

注意:

题目并不难,只是中间犯了很多错误;

1、对于i=0以及j=0的行和列忘记累加求和;

2、在根据中间结果计算最终结果时,公式求错;

3、根据自己所用公式,在边界值时忘记处理;

4、其余一些小错误;

附:

sum = vector<vector<int> >(matrix);

 1 class NumMatrix {
 2 public:
 3     NumMatrix(vector<vector<int> > &matrix) {
 4         int m = matrix.size();
 5         if(m==0)
 6             return;
 7         int n = matrix[0].size();
 8         sum = vector<vector<int> >(matrix);
 9 
10         for(int i=1;i<n;i++)
11         {
12             sum[0][i] += sum[0][i-1];
13         }
14         for(int i=1;i<m;i++)
15         {
16             sum[i][0] += sum[i-1][0];
17 
18         }
19         for(int i=1;i<m;i++)
20         {
21             for(int j=1;j<n;j++)
22             {
23                 sum[i][j] += sum[i][j-1]+sum[i-1][j]-sum[i-1][j-1];
24             }
25         }
26     }
27 
28     int sumRegion(int row1, int col1, int row2, int col2) {
29         int ans = sum[row2][col2];
30         if(col1>0)
31             ans -= sum[row2][col1-1];
32         if(row1>0)
33             ans -= sum[row1-1][col2];
34         if(row1>0&&col1>0)
35             ans += sum[row1-1][col1-1];
36         return ans;
37     }
38 
39     vector<vector<int> > sum;
40 };
41 
42 
43 
44 // Your NumMatrix object will be instantiated and called as such:
45 // NumMatrix numMatrix(matrix);
46 // numMatrix.sumRegion(0, 1, 2, 3);
47 // numMatrix.sumRegion(1, 2, 3, 4);
View Code
原文地址:https://www.cnblogs.com/jsir2016bky/p/5759848.html