Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e5a6b93

Browse files
🐱(dynamic): 304. 二维区域和检索 - 矩阵不可变
1 parent 7f633e4 commit e5a6b93

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

‎docs/algorithm/dynamic/README.md‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1134,6 +1134,34 @@ func (this *NumArray) SumRange(i int, j int) int {
11341134

11351135
<!-- tabs:end -->
11361136

1137+
## 304. 二维区域和检索 - 矩阵不可变
1138+
1139+
[原题链接](https://leetcode-cn.com/problems/range-sum-query-2d-immutable/)
1140+
1141+
### 解法一:二维前缀和
1142+
1143+
```python
1144+
class NumMatrix:
1145+
1146+
def __init__(self, matrix: List[List[int]]):
1147+
m = len(matrix)
1148+
n = len(matrix[0]) if matrix else 0
1149+
self.sums = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
1150+
1151+
for i in range(m):
1152+
for j in range(n):
1153+
self.sums[i + 1][j + 1] = self.sums[i][j + 1] + self.sums[i + 1][j] - self.sums[i][j] + matrix[i][j]
1154+
1155+
1156+
def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
1157+
return self.sums[row2 + 1][col2 + 1] - self.sums[row2 + 1][col1] - self.sums[row1][col2 + 1] + self.sums[row1][col1]
1158+
1159+
1160+
# Your NumMatrix object will be instantiated and called as such:
1161+
# obj = NumMatrix(matrix)
1162+
# param_1 = obj.sumRegion(row1,col1,row2,col2)
1163+
```
1164+
11371165
## 309. 最佳买卖股票时机含冷冻期
11381166

11391167
[原题链接](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /