Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit f6a0b42

Browse files
aQuaaQua
aQua
authored and
aQua
committed
480 added
1 parent aee3850 commit f6a0b42

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# [480. Sliding Window Median](https://leetcode.com/problems/sliding-window-median/)
2+
3+
## 题目
4+
5+
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
6+
7+
Examples:
8+
9+
[2,3,4] , the median is 3
10+
11+
[2,3], the median is (2 + 3) / 2 = 2.5
12+
13+
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Your job is to output the median array for each window in the original array.
14+
15+
For example,
16+
17+
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
18+
19+
```text
20+
Window position Median
21+
--------------- -----
22+
[1 3 -1] -3 5 3 6 7 1
23+
1 [3 -1 -3] 5 3 6 7 -1
24+
1 3 [-1 -3 5] 3 6 7 -1
25+
1 3 -1 [-3 5 3] 6 7 3
26+
1 3 -1 -3 [5 3 6] 7 5
27+
1 3 -1 -3 5 [3 6 7] 6
28+
```
29+
30+
Therefore, return the median sliding window as [1,-1,-1,3,5,6].
31+
32+
Note:
33+
You may assume k is always valid, ie: k is always smaller than input array's size for non-empty array.
34+
35+
## 解题思路
36+
37+
见程序注释
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package Problem0480
2+
3+
func medianSlidingWindow(nums []int, k int) []float64 {
4+
res :=
5+
6+
return res
7+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package Problem0480
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
// tcs is testcase slice
11+
var tcs = []struct {
12+
nums []int
13+
k int
14+
ans []float64
15+
}{
16+
17+
{
18+
[]int{1, 3, -1, -3, 5, 3, 6, 7},
19+
3,
20+
[]float64{1, -1, -1, 3, 5, 6},
21+
},
22+
23+
// 可以有多个 testcase
24+
}
25+
26+
func Test_medianSlidingWindow(t *testing.T) {
27+
ast := assert.New(t)
28+
29+
for _, tc := range tcs {
30+
fmt.Printf("~~%v~~\n", tc)
31+
ast.Equal(tc.ans, medianSlidingWindow(tc.nums, tc.k), "输入:%v", tc)
32+
}
33+
}
34+
35+
func Benchmark_medianSlidingWindow(b *testing.B) {
36+
for i := 0; i < b.N; i++ {
37+
for _, tc := range tcs {
38+
medianSlidingWindow(tc.nums, tc.k)
39+
}
40+
}
41+
}

0 commit comments

Comments
 (0)