在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ In an array Example 1: Input: A = 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 = [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] 提示:
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 } 232ms 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 } 304ms 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 }
|
请发表评论