★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-wtytrqpf-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
In an array A
of 0
s and 1
s, how many non-empty subarrays have sum S
?git
Example 1:github
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 either 0
or 1
.在由若干 0
和 1
組成的數組 A
中,有多少個和爲 S
的非空子數組。微信
示例:app
輸入: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]
提示:spa
A.length <= 30000
0 <= S <= A.length
A[i]
爲 0
或 1
220mscode
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 }
232mshtm
1 class Solution { 2 func numSubarraysWithSum(_ A: [Int], _ S: Int) -> Int { 3 4 var count = 0 5 var zCount = 0 6 var prevVal = 0 7 if S == 0 { 8 for val in A { 9 if val == 0 { 10 print(zCount) 11 prevVal += 1 12 zCount += prevVal 13 } else { 14 count += zCount 15 zCount = 0 16 prevVal = 0 17 } 18 } 19 count += zCount 20 return count 21 } 22 23 var leftZeros:[Int] = Array(repeating: 0, count: A.count) 24 var rightZeros:[Int] = Array(repeating: 0, count: A.count) 25 var onesInd:[Int] = [] 26 27 28 for i in 0..<A.count { 29 if A[i] == 0 { 30 count += 1 31 } else { 32 leftZeros[i] = count 33 onesInd.append(i) 34 count = 0 35 } 36 } 37 38 count = 0 39 for i in (0..<A.count).reversed() { 40 if A[i] == 0 { 41 count += 1 42 }else { 43 rightZeros[i] = count 44 count = 0 45 } 46 } 47 48 if onesInd.count < S { 49 return 0 50 } 51 52 count = 0 53 for i in 0...(onesInd.count - S) { 54 let leftInd = onesInd[i] 55 let rightInd = onesInd[i + S - 1] 56 let subCount = (1 + leftZeros[leftInd]) * (rightZeros[rightInd] + 1) 57 count += subCount 58 } 59 return count 60 } 61 }
304msblog
1 class Solution { 2 func numSubarraysWithSum(_ A: [Int], _ S: Int) -> Int { 3 var counter = 0 4 var dp = [Int](repeating: 0, count: A.count + 1) 5 for i in 0..<A.count { 6 counter += A[i] 7 dp[i + 1] = counter 8 } 9 var result = 0 10 var dict = [Int : Int]() 11 dict[0] = 1 12 for i in 1..<dp.count { 13 let a = dp[i] 14 if let value = dict[a - S] { 15 result += value 16 } 17 dict[a] = dict[a] ?? 0 18 dict[a] = dict[a]! + 1 19 } 20 return result 21 } 22 }