304. Range Sum Query 2D - Immutable

  • 23.4%

https://leetcode.com/problems/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).

image

The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.

1
2
3
4
5
6
7
8
9
10
11
12
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.

cpp


https://discuss.leetcode.com/topic/29536/clean-c-solution-and-explaination-o-mn-space-with-o-1-time

Clean C++ Solution and Explaination - O(mn) space with O(1) time

Construct a 2D array sums[row+1][col+1]

(notice: we add additional blank row sums[0][col+1]={0} and blank column sums[row+1][0]={0} to remove the edge case checking), so, we can have the following definition

sums[i+1][j+1] represents the sum of area from matrix[0][0] to matrix[i][j]

To calculate sums, the ideas as below

1
2
3
4
5
6
7
8
9
10
11
12
13
+-----+-+-------+     +--------+-----+     +-----+---------+     +-----+--------+
| | | | | | | | | | | | |
| | | | | | | | | | | | |
+-----+-+ | +--------+ | | | | +-----+ |
| | | | = | | + | | | - | |
+-----+-+ | | | +-----+ | | |
| | | | | | | |
| | | | | | | |
+---------------+ +--------------+ +---------------+ +--------------+

sums[i][j] = sums[i-1][j] + sums[i][j-1] - sums[i-1][j-1] +

matrix[i-1][j-1]

So, we use the same idea to find the specific area’s sum.

1
2
3
4
5
6
7
8
9
+---------------+   +--------------+   +---------------+   +--------------+   +--------------+
| | | | | | | | | | | | | |
| (r1,c1) | | | | | | | | | | | | |
| +------+ | | | | | | | +---------+ | +---+ |
| | | | = | | | - | | | - | (r1,c2) | + | (r1,c1) |
| | | | | | | | | | | | | |
| +------+ | +---------+ | +---+ | | | | |
| (r2,c2)| | (r2,c2)| | (r2,c1) | | | | |
+---------------+ +--------------+ +---------------+ +--------------+ +--------------+

And we can have the following code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class NumMatrix {
private:
int row, col;
vector<vector<int>> sums;
public:
NumMatrix(vector<vector<int>> &matrix) {
row = matrix.size();
col = row>0 ? matrix[0].size() : 0;
sums = vector<vector<int>>(row+1, vector<int>(col+1, 0));
for(int i=1; i<=row; i++) {
for(int j=1; j<=col; j++) {
sums[i][j] = matrix[i-1][j-1] +
sums[i-1][j] + sums[i][j-1] - sums[i-1][j-1] ;
}
}
}

int sumRegion(int row1, int col1, int row2, int col2) {
return sums[row2+1][col2+1] - sums[row2+1][col1] - sums[row1][col2+1] + sums[row1][col1];
}
};

https://discuss.leetcode.com/topic/29401/c-with-helper

C++ with helper

My accu[i][j] is the sum of matrix[0..i][0..j], and a(i, j) helps with edge cases.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class NumMatrix {
public:
NumMatrix(vector<vector<int>> &matrix) {
accu = matrix;
for (int i=0; i<matrix.size(); ++i)
for (int j=0; j<matrix[0].size(); ++j)
accu[i][j] += a(i-1, j) + a(i, j-1) - a(i-1, j-1);
}

int sumRegion(int row1, int col1, int row2, int col2) {
return a(row2, col2) - a(row1-1, col2) - a(row2, col1-1) + a(row1-1, col1-1);
}

private:
vector<vector<int>> accu;
int a(int i, int j) {
return i >= 0 && j >= 0 ? accu[i][j] : 0;
}
};

Afterthought

Instead of

1
accu[i][j] += a(i-1, j) + a(i, j-1) - a(i-1, j-1);

I could use

1
accu[i][j] += a(i, j) - sumRegion(i, j, i, j);

which is shorter but I think less clear. I do like already using sumRegion in the precomputation, though.


my code:

注意中间那句,n = m>0? matrix[0].size() : 0;m可能为0的情况。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class NumMatrix {
public:
NumMatrix(vector<vector<int>> matrix) {
m = matrix.size();
n = m>0? matrix[0].size() : 0;
dp = vector<vector<int>>(m+1, vector<int>(n+1, 0));
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
dp[i+1][j+1] = matrix[i][j] + dp[i+1][j] + dp[i][j+1] - dp[i][j];
}
}
}

int sumRegion(int row1, int col1, int row2, int col2) {
return dp[row2+1][col2+1] + dp[row1][col1] - dp[row2+1][col1] - dp[row1][col2+1];
}
private:
int m, n;
vector<vector<int>> dp;
};

/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix obj = new NumMatrix(matrix);
* int param_1 = obj.sumRegion(row1,col1,row2,col2);
*/

python


https://discuss.leetcode.com/topic/29354/sharing-my-python-solution

Sharing My Python solution

The idea is simple, just precompute sums for all matrices with (0, 0) as top left corner and (i, j) as bottom right corner. There are O(n^2) of these matrices, so we store them in a 2D table. In order to make code simpler, I add an extra column and row, filled with 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class NumMatrix(object):
def __init__(self, matrix):
if matrix is None or not matrix:
return
n, m = len(matrix), len(matrix[0])
self.sums = [ [0 for j in xrange(m+1)] for i in xrange(n+1) ]
for i in xrange(1, n+1):
for j in xrange(1, m+1):
self.sums[i][j] = matrix[i-1][j-1] + self.sums[i][j-1] + self.sums[i-1][j] - self.sums[i-1][j-1]


def sumRegion(self, row1, col1, row2, col2):
row1, col1, row2, col2 = row1+1, col1+1, row2+1, col2+1
return self.sums[row2][col2] - self.sums[row2][col1-1] - self.sums[row1-1][col2] + self.sums[row1-1][col1-1]

java


https://discuss.leetcode.com/topic/29355/clean-and-easy-to-understand-java-solution

Clean and easy to understand java solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
private int[][] dp;

public NumMatrix(int[][] matrix) {
if( matrix == null
|| matrix.length == 0
|| matrix[0].length == 0 ){
return;
}

int m = matrix.length;
int n = matrix[0].length;

dp = new int[m + 1][n + 1];
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
dp[i][j] = dp[i - 1][j] + dp[i][j - 1] -dp[i - 1][j - 1] + matrix[i - 1][j - 1] ;
}
}
}

public int sumRegion(int row1, int col1, int row2, int col2) {
int iMin = Math.min(row1, row2);
int iMax = Math.max(row1, row2);

int jMin = Math.min(col1, col2);
int jMax = Math.max(col1, col2);

return dp[iMax + 1][jMax + 1] - dp[iMax + 1][jMin] - dp[iMin][jMax + 1] + dp[iMin][jMin];
}
谢谢你,可爱的朋友。