Skip to content

Commit 3ff1e32

Browse files
committed
✨ Add solution and testcases to problem 718
1 parent 7aea5dc commit 3ff1e32

File tree

3 files changed

+40
-15
lines changed

3 files changed

+40
-15
lines changed

leetcode/701-800/0718.Maximum-Length-of-Repeated-Subarray/README.md

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,21 @@
11
# [718.Maximum Length of Repeated Subarray][title]
22

3-
> [!WARNING|style:flat]
4-
> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm)
5-
63
## Description
74

5+
Given two integer arrays `nums1` and `nums2`, return _the maximum length of a subarray that appears in **both** arrays_.
6+
87
**Example 1:**
98

109
```
11-
Input: a = "11", b = "1"
12-
Output: "100"
10+
Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
11+
Output: 3
12+
```
13+
14+
**Example 2:**
15+
16+
```
17+
Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]
18+
Output: 5
1319
```
1420

1521
## 题意
Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,23 @@
11
package Solution
22

3-
func Solution(x bool) bool {
4-
return x
3+
func Solution(nums1 []int, nums2 []int) int {
4+
n, m := len(nums1), len(nums2);
5+
dp := make([]int, m + 1);
6+
res := 0;
7+
for i := 1; i < n + 1; i++ {
8+
for j := m; j > 0; j-- {
9+
if nums1[i - 1] == nums2[j - 1] {
10+
dp[j] = 1 + dp[j - 1];
11+
} else {
12+
dp[j] = 0;
13+
}
14+
res = max(res, dp[j])
15+
}
16+
}
17+
return res;
18+
}
19+
20+
func max(v1, v2 int) int {
21+
if v1 > v2 { return v1; }
22+
return v2;
523
}

leetcode/701-800/0718.Maximum-Length-of-Repeated-Subarray/Solution_test.go

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,21 +10,22 @@ func TestSolution(t *testing.T) {
1010
// 测试用例
1111
cases := []struct {
1212
name string
13-
inputs bool
14-
expect bool
13+
nums1 []int
14+
nums2 []int
15+
expect int
1516
}{
16-
{"TestCase", true, true},
17-
{"TestCase", true, true},
18-
{"TestCase", false, false},
17+
{"TestCase", []int{1,2,3,2,1}, []int{3,2,1,4,7}, 3},
18+
{"TestCase", []int{0,0,0,0,0}, []int{0,0,0,0,0}, 5},
19+
{"TestCase", []int{0,0,0,0,1}, []int{1,0,0,0,0}, 4},
1920
}
2021

2122
// 开始测试
2223
for i, c := range cases {
2324
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
24-
got := Solution(c.inputs)
25+
got := Solution(c.nums1, c.nums2)
2526
if !reflect.DeepEqual(got, c.expect) {
26-
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
27-
c.expect, got, c.inputs)
27+
t.Fatalf("expected: %v, but got: %v, with inputs: %v %v",
28+
c.expect, got, c.nums1, c.nums2)
2829
}
2930
})
3031
}

0 commit comments

Comments
 (0)