Skip to content

Commit cc8d034

Browse files
authored
304 solved. (#77)
1 parent 11fb1ef commit cc8d034

File tree

3 files changed

+71
-1
lines changed

3 files changed

+71
-1
lines changed

src/0211_add_and_search_word/add_and_search_word_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import "testing"
55
func TestAddAndSearchWord(t *testing.T) {
66
obj := Constructor()
77

8-
for _, word := range []string{"bad", "dad", "mad"}{
8+
for _, word := range []string{"bad", "dad", "mad"} {
99
obj.AddWord(word)
1010
}
1111

src/304_Range_Sum_Query_2D/rsq.go

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
304. Range Sum Query 2D - Immutable
3+
https://leetcode.com/problems/range-sum-query-2d-immutable/
4+
*/
5+
// 2019-02-27
6+
7+
package rsq
8+
9+
// NumMatrix 累计区域和的数组
10+
type NumMatrix struct {
11+
dp [][]int
12+
}
13+
14+
// Constructor 初始化构造函数
15+
func Constructor(matrix [][]int) NumMatrix {
16+
if len(matrix) == 0 || len(matrix[0]) == 0 {
17+
return NumMatrix{}
18+
}
19+
numMatrix := NumMatrix{dp: make([][]int, len(matrix)+1)}
20+
for i := 0; i < len(numMatrix.dp); i++ {
21+
numMatrix.dp[i] = make([]int, len(matrix[0])+1)
22+
}
23+
24+
for i := 1; i <= len(matrix); i++ {
25+
for j := 1; j <= len(matrix[0]); j++ {
26+
numMatrix.dp[i][j] = numMatrix.dp[i-1][j] + numMatrix.dp[i][j-1] - numMatrix.dp[i-1][j-1] + matrix[i-1][j-1]
27+
}
28+
}
29+
return numMatrix
30+
}
31+
32+
// SumRegion 求区域和
33+
func (nm *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int) int {
34+
return nm.dp[row2+1][col2+1] - nm.dp[row1][col2+1] - nm.dp[row2+1][col1] + nm.dp[row1][col1]
35+
}
+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package rsq
2+
3+
import "testing"
4+
5+
func TestSunRegion(t *testing.T) {
6+
matrix := [][]int{
7+
{3, 0, 1, 4, 2},
8+
{5, 6, 3, 2, 1},
9+
{1, 2, 0, 1, 5},
10+
{4, 1, 0, 1, 7},
11+
{1, 0, 3, 0, 5},
12+
}
13+
14+
obj := Constructor(matrix)
15+
16+
testData := [][]int{
17+
{2, 1, 4, 3},
18+
{1, 1, 2, 2},
19+
{1, 2, 2, 4},
20+
}
21+
expected := []int{8, 11, 12}
22+
23+
for index, data := range testData {
24+
if res := obj.SumRegion(data[0], data[1], data[2], data[3]); res != expected[index] {
25+
t.Errorf("expected %d, got %d", expected[index], res)
26+
}
27+
}
28+
29+
if res := Constructor([][]int{}); res.dp != nil {
30+
t.Errorf("expected nil, got %v", res.dp)
31+
}
32+
if res := Constructor(make([][]int, 3)); res.dp != nil {
33+
t.Errorf("expected nil, got %v", res.dp)
34+
}
35+
}

0 commit comments

Comments
 (0)