Skip to content

Commit 6e89d31

Browse files
aQuaaQua
aQua
authored and
aQua
committed
209 accepted
1 parent 52b20e2 commit 6e89d31

File tree

3 files changed

+120
-0
lines changed

3 files changed

+120
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# [209. Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/)
2+
3+
## 题目
4+
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
5+
6+
For example, given the array `[2,3,1,2,4,3]` and s = `7`,
7+
the subarray `[4,3]` has the minimal length under the problem constraint.
8+
9+
**More practice:**
10+
11+
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
12+
13+
## 解题思路
14+
15+
见程序注释
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package Problem0209
2+
3+
func minSubArrayLen(s int, a []int) int {
4+
n := len(a)
5+
6+
if n == 0 {
7+
return 0
8+
}
9+
10+
res, i, j, sum := n+1, 0, 0, 0
11+
12+
for j < n {
13+
sum += a[j]
14+
j++
15+
16+
for sum >= s {
17+
sum -= a[i]
18+
i++
19+
if res > j-i+1 {
20+
res = j - i + 1
21+
}
22+
}
23+
}
24+
25+
return res % (n + 1)
26+
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package Problem0209
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
type question struct {
11+
para
12+
ans
13+
}
14+
15+
// para 是参数
16+
type para struct {
17+
s int
18+
nums []int
19+
}
20+
21+
// ans 是答案
22+
type ans struct {
23+
one int
24+
}
25+
26+
func Test_Problem0209(t *testing.T) {
27+
ast := assert.New(t)
28+
29+
qs := []question{
30+
31+
question{
32+
para{
33+
15,
34+
[]int{1, 2, 3, 4, 5},
35+
},
36+
ans{
37+
5,
38+
},
39+
},
40+
41+
question{
42+
para{
43+
700,
44+
[]int{2, 3, 1, 2, 4, 3},
45+
},
46+
ans{
47+
0,
48+
},
49+
},
50+
51+
question{
52+
para{
53+
7,
54+
[]int{2, 3, 1, 2, 4, 3},
55+
},
56+
ans{
57+
2,
58+
},
59+
},
60+
61+
question{
62+
para{
63+
7,
64+
[]int{},
65+
},
66+
ans{
67+
0,
68+
},
69+
},
70+
// 如需多个测试,可以复制上方元素。
71+
}
72+
73+
for _, q := range qs {
74+
a, p := q.ans, q.para
75+
fmt.Printf("~~%v~~\n", p)
76+
77+
ast.Equal(a.one, minSubArrayLen(p.s, p.nums), "输入:%v", p)
78+
}
79+
}

0 commit comments

Comments
 (0)