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 (_row_1, _col_1) and lower right corner (_row_2, _col_2).
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.
Example:
1
2
3
4
5
6
7
8
9
10
11 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) -> 12Note:
- You may assume that the matrix does not change.
- There are many calls to sumRegion function.
- You may assume that _row_1 ≤ _row_2 and _col_1 ≤ _col_2.
题目地址 leetcode Range Sum Query 2D - Immutable
题意:
给定一个矩阵,和两个矩阵的坐标(row1,col1),(row2,col2),让你计算他们之间元素的和
思路:
和之前的那题leetcode Range Sum Query – Immutable很像,只不过这次用二维数组进行和的存储。
记得多减去的要加回来~
Code:
1 | class NumMatrix(object): |