Skip to content

Commit 2244cee

Browse files
aQuaaQua
aQua
authored and
aQua
committed
643 通过单元测试
1 parent 6a0d031 commit 2244cee

File tree

3 files changed

+33
-7
lines changed

3 files changed

+33
-7
lines changed

Algorithms/0643.maximum-average-subarray-i/README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,17 @@
11
# [643. Maximum Average Subarray I](https://leetcode.com/problems/maximum-average-subarray-i/)
22

33
## 题目
4+
Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.
45

6+
Example 1:
7+
```
8+
Input: [1,12,-5,-6,50,3], k = 4
9+
Output: 12.75
10+
Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
11+
```
12+
Note:
13+
1 <= k <= n <= 30,000.
14+
Elements of the given array will be in the range [-10,000, 10,000].
515

616
## 解题思路
717

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,17 @@
11
package Problem0643
22

3+
func findMaxAverage(nums []int, k int) float64 {
4+
max := 0
5+
6+
for i := 0; i+k-1 < len(nums); i++ {
7+
temp := 0
8+
for j := i; j < i+k; j++ {
9+
temp += nums[j]
10+
}
11+
if max < temp {
12+
max = temp
13+
}
14+
}
15+
16+
return float64(max) / float64(k)
17+
}
Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
package Problem0643
22

33
import (
4-
"testing"
54
"fmt"
5+
"testing"
66

77
"github.com/stretchr/testify/assert"
88
)
@@ -15,13 +15,14 @@ type question struct {
1515
// para 是参数
1616
// one 代表第一个参数
1717
type para struct {
18-
one string
18+
nums []int
19+
k int
1920
}
2021

2122
// ans 是答案
2223
// one 代表第一个答案
2324
type ans struct {
24-
one string
25+
one float64
2526
}
2627

2728
func Test_Problem0643(t *testing.T) {
@@ -30,17 +31,17 @@ func Test_Problem0643(t *testing.T) {
3031
qs := []question{
3132

3233
question{
33-
para{""},
34-
ans{""},
34+
para{[]int{1, 12, -5, -6, 50, 3}, 4},
35+
ans{12.75},
3536
},
36-
37+
3738
// 如需多个测试,可以复制上方元素。
3839
}
3940

4041
for _, q := range qs {
4142
a, p := q.ans, q.para
4243
fmt.Printf("~~%v~~\n", p)
4344

44-
ast.Equal(a.one, (p.one), "输入:%v", p)
45+
ast.Equal(a.one, findMaxAverage(p.nums, p.k), "输入:%v", p)
4546
}
4647
}

0 commit comments

Comments
 (0)