Skip to content

Commit aeec681

Browse files
committed
930 finish
1 parent b66fbb1 commit aeec681

File tree

2 files changed

+41
-26
lines changed

2 files changed

+41
-26
lines changed

Algorithms/0930.binary-subarrays-with-sum/binary-subarrays-with-sum.go

Lines changed: 35 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -4,48 +4,57 @@ func numSubarraysWithSum(A []int, S int) int {
44
if S == 0 {
55
return zero(A)
66
}
7+
return nonZero(A, S)
8+
}
79

10+
func zero(A []int) int {
11+
res, count := 0, 0
12+
for _, n := range A {
13+
if n == 0 {
14+
count++
15+
res += count
16+
} else {
17+
count = 0
18+
}
19+
}
20+
return res
21+
}
22+
23+
func nonZero(A []int, S int) int {
824
size := len(A)
9-
i, j, sum := 0, 0, 0
1025

11-
for j < size && sum < S {
12-
sum += A[j]
13-
j++
26+
end, sum := 0, 0
27+
for end < size && sum < S {
28+
sum += A[end]
29+
end++
1430
}
1531

16-
res := 0
17-
for i < size && j <= size && sum == S {
32+
if sum != S {
33+
// A 中所有的 1 加起来都比 S 小
34+
return 0
35+
}
36+
37+
begin, res := 0, 0
38+
for begin < size && end <= size {
1839
left := 1
19-
for i < j && A[i] == 0 {
20-
i++
40+
for begin < size && A[begin] == 0 {
41+
begin++
2142
left++
2243
}
2344

2445
right := 1
25-
for j < size && A[j] == 0 {
26-
j++
46+
for end < size && A[end] == 0 {
47+
end++
2748
right++
2849
}
2950

3051
res += left * right
3152

32-
i++
33-
j++
53+
// 此时, A[begin] == A[end] == 1
54+
begin++ // 相当于 sum--
55+
end++ // 相当于 sum++
56+
// 所以, sum 保持不变
3457
}
3558

3659
return res
3760
}
38-
39-
func zero(A []int) int {
40-
res := 0
41-
tmp := 0
42-
for _, a := range A {
43-
if a == 1 {
44-
tmp = 0
45-
} else {
46-
tmp++
47-
res += tmp
48-
}
49-
}
50-
return res
51-
}

Algorithms/0930.binary-subarrays-with-sum/binary-subarrays-with-sum_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@ var tcs = []struct {
1313
ans int
1414
}{
1515

16+
{
17+
[]int{1, 1, 1, 1, 1, 1, 1, 1},
18+
6,
19+
3,
20+
},
21+
1622
{
1723
[]int{0, 0, 0, 0, 0, 0, 1, 0, 0, 0},
1824
0,

0 commit comments

Comments
 (0)