In an array A
of 0
s and 1
s,how many non-empty subarrays have sum S
?
Example 1:
input: A = [1,1,1],S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [1,1] [1,1]
Note:
A.length <= 30000
0 <= S <= A.length
A[i]
is either 0
or 1
. 在由若干 0
和 1
组成的数组 A
中,有多少个和为 S
的非空子数组。
示例:
输入:A = [1,S = 2输出:4解释:如下面黑体所示,有 4 个满足题目要求的子数组:[1,1][1,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 = 011 var f:[Int] = [Int](repeating: 0,count: 30003)12 for i in 0...n13 {14 if cum[i] - S >= 015 {16 ret += f[cum[i] - S]17 }18 f[cum[i]] += 119 }20 return ret21 }22 }总结
以上是内存溢出为你收集整理的[Swift Weekly Contest 108]LeetCode930. 和相同的二元子数组 | Binary Subarrays With Sum全部内容,希望文章能够帮你解决[Swift Weekly Contest 108]LeetCode930. 和相同的二元子数组 | Binary Subarrays With Sum所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)