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 19fcfd2

Browse files
committed
add 304
1 parent d5d2d78 commit 19fcfd2

File tree

4 files changed

+93
-0
lines changed

4 files changed

+93
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
2+
# 0304.range-sum-query-2d-immutable
3+
4+
![链表](../../static/image/304.png)
5+
6+
```text
7+
304. 二维区域和检索 - 矩阵不可变
8+
9+
给定一个二维矩阵,计算其子矩形范围内元素的总和,该子矩阵的左上角为 (row1, col1) ,右下角为 (row2, col2) 。
10+
11+
12+
上图子矩阵左上角 (row1, col1) = (2, 1) ,右下角(row2, col2) = (4, 3),该子矩形内元素的总和为 8。
13+
14+
15+
16+
示例:
17+
18+
给定 matrix = [
19+
[3, 0, 1, 4, 2],
20+
[5, 6, 3, 2, 1],
21+
[1, 2, 0, 1, 5],
22+
[4, 1, 0, 1, 7],
23+
[1, 0, 3, 0, 5]
24+
]
25+
26+
sumRegion(2, 1, 4, 3) -> 8
27+
sumRegion(1, 1, 2, 2) -> 11
28+
sumRegion(1, 2, 2, 4) -> 12
29+
30+
31+
提示:
32+
33+
你可以假设矩阵不可变。
34+
会多次调用 sumRegion 方法。
35+
你可以假设 row1 ≤ row2 且 col1 ≤ col2 。
36+
37+
来源:力扣(LeetCode)
38+
链接:https://leetcode-cn.com/problems/range-sum-query-2d-immutable
39+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
40+
```
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package immutable
2+
3+
import "fmt"
4+
5+
func Run() {
6+
matrix := [][]int{
7+
[]int{3, 0, 1, 4, 2},
8+
[]int{5, 6, 3, 2, 1},
9+
[]int{1, 2, 0, 1, 5},
10+
[]int{4, 1, 0, 1, 7},
11+
[]int{1, 0, 3, 0, 5},
12+
}
13+
c := Constructor(matrix)
14+
sum := c.SumRegion(2, 1, 4, 3)
15+
fmt.Println(sum)
16+
}
17+
18+
type NumMatrix struct {
19+
sums [][]int
20+
}
21+
22+
func Constructor(matrix [][]int) NumMatrix {
23+
sums := make([][]int, len(matrix))
24+
for i, row := range matrix {
25+
sums[i] = make([]int, len(row)+1)
26+
for i2, v := range row {
27+
sums[i][i2+1] = sums[i][i2] + v
28+
}
29+
}
30+
return NumMatrix{sums: sums}
31+
}
32+
33+
func (this *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int {
34+
sum := 0
35+
for i := row1; i <= row2; i++ {
36+
sum += this.sums[i][col2+1] - this.sums[i][col1]
37+
}
38+
return sum
39+
}
40+
41+
/**
42+
* Your NumMatrix object will be instantiated and called as such:
43+
* obj := Constructor(matrix);
44+
* param_1 := obj.SumRegion(row1,col1,row2,col2);
45+
*/
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
2+
package immutable
3+
4+
import "testing"
5+
6+
func TestRun(t *testing.T) {
7+
Run()
8+
}

‎static/image/304.png‎

41.4 KB
Loading[フレーム]

0 commit comments

Comments
(0)

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