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 1614d48

Browse files
🐱(dynamic): 304. 二维区域和检索 - 矩阵不可变
更新 Golang 解法
1 parent e5a6b93 commit 1614d48

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

‎docs/algorithm/dynamic/README.md‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1140,6 +1140,10 @@ func (this *NumArray) SumRange(i int, j int) int {
11401140

11411141
### 解法一:二维前缀和
11421142

1143+
<!-- tabs:start -->
1144+
1145+
#### **Python**
1146+
11431147
```python
11441148
class NumMatrix:
11451149

@@ -1162,6 +1166,48 @@ class NumMatrix:
11621166
# param_1 = obj.sumRegion(row1,col1,row2,col2)
11631167
```
11641168

1169+
#### **Go**
1170+
1171+
```go
1172+
type NumMatrix struct {
1173+
sums [][]int
1174+
}
1175+
1176+
1177+
func Constructor(matrix [][]int) NumMatrix {
1178+
m := len(matrix)
1179+
if m == 0 {
1180+
return NumMatrix{}
1181+
}
1182+
n := len(matrix[0])
1183+
sums := make([][]int, m + 1)
1184+
// 初始化第 0 行
1185+
sums[0] = make([]int, n + 1)
1186+
for i, row := range matrix {
1187+
sums[i + 1] = make([]int, n + 1)
1188+
for j, num := range row {
1189+
sums[i + 1][j + 1] = sums[i][j + 1] + sums[i + 1][j] - sums[i][j] + num
1190+
}
1191+
}
1192+
1193+
return NumMatrix{sums}
1194+
}
1195+
1196+
1197+
func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int {
1198+
return this.sums[row2 + 1][col2 + 1] - this.sums[row2 + 1][col1] - this.sums[row1][col2 + 1] + this.sums[row1][col1]
1199+
}
1200+
1201+
1202+
/**
1203+
* Your NumMatrix object will be instantiated and called as such:
1204+
* obj := Constructor(matrix);
1205+
* param_1 := obj.SumRegion(row1,col1,row2,col2);
1206+
*/
1207+
```
1208+
1209+
<!-- tabs:end -->
1210+
11651211
## 309. 最佳买卖股票时机含冷冻期
11661212

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

0 commit comments

Comments
(0)

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