In an array A
of 0
s and 1
s, how many non-empty subarrays have sum S
?
Example 1:
Input: A = [1,0,1,0,1], S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]
Note:
A.length <= 30000
0 <= S <= A.length
A[i]
is either0
or1
.
在由若干
0
和 1
组成的数组 A
中,有多少个和为 S
的非空子数组。
示例:
输入:A = [1,0,1,0,1], S = 2 输出:4 解释: 如下面黑体所示,有 4 个满足题目要求的子数组: [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1] [1,0,1,0,1]
提示:
A.length <= 30000
0 <= S <= A.length
A[i]
为0
或1
220ms
1 class Solution { 2 func numSubarraysWithSum(_ A: [Int], _ S: Int) -> Int { 3 var n:Int = A.count 4 var cum:[Int] = [Int](repeating: 0,count: n + 1) 5 for i in 0..<n 6 { 7 cum[i + 1] = cum[i] + A[i] 8 } 9 10 var ret:Int = 0 11 var f:[Int] = [Int](repeating: 0,count: 30003) 12 for i in 0...n 13 { 14 if cum[i] - S >= 0 15 { 16 ret += f[cum[i] - S] 17 } 18 f[cum[i]] += 1 19 } 20 return ret 21 } 22 }
原文地址:https://www.cnblogs.com/strengthen/p/9865173.html
时间: 2024-10-10 12:43:23