Fork me on GitHub

08. 找到符合确切条件的子数组数

正文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
fun numSubarraysWithSum(nums: IntArray, goal: Int): Int {
var count = 0
var total = 0
var left = 0

for (right in nums.indices) {
total += nums[right]

while (left <= right && total > goal) {
total -= nums[left]
left++
}

if (total == goal) {
count++

// 统计连续的0
var temp = left
while (temp <= right && nums[temp] == 0) {
count++
temp++
}
}
}

return count
}
,