微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[Swift Weekly Contest 108]LeetCode930. 和相同的二元子数组 | Binary Subarrays With Sum

In an array A of 0s and 1s,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:

  1. A.length <= 30000
  2. 0 <= S <= A.length
  3. A[i] is either 0 or 1.

在由若干 0 和 1  组成的数组 A 中,有多少个和为 S 的非空子数组。

 示例:

输入:A = [1,S = 2
输出:4
解释:
如下面黑体所示,有 4 个满足题目要求的子数组:
[1,1]
[1,1]

 提示

  1. A.length <= 30000
  2. 0 <= S <= A.length
  3. 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 }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐