Leetcode-930 Binary Subarrays With Sum(和相同的二元子数组)
Posted Asurudo Jyo の 倉 庫
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode-930 Binary Subarrays With Sum(和相同的二元子数组)相关的知识,希望对你有一定的参考价值。
1 class Solution 2 { 3 public: 4 int numSubarraysWithSum(vector<int>& A, int S) 5 { 6 if(S==0) 7 { 8 int result = 0; 9 int count = 0; 10 for(int i = 0; i < A.size(); i ++) 11 { 12 if(A[i]==0) 13 count ++; 14 else 15 { 16 result += (count+1)*count/2; 17 count = 0; 18 } 19 } 20 if(count) 21 { 22 result += (count+1)*count/2; 23 count = 0; 24 } 25 return result; 26 } 27 int totalResult = 0; 28 29 int left = 0,right = 0; 30 int oneSum = 0; 31 int result = 0; 32 for(; right < A.size(); right ++) 33 { 34 if(oneSum < S) 35 { 36 if(A[right]==1) 37 oneSum ++; 38 } 39 if(oneSum == S) 40 { 41 int leftResult = 1,rightResult = 1; 42 while(right != A.size()-1 && A[right+1]==0) 43 { 44 right ++; 45 rightResult ++; 46 } 47 if(A[left]==1) 48 ; 49 else 50 { 51 while(left < right && A[left+1]==0) 52 { 53 left ++; 54 leftResult ++; 55 } 56 left ++; 57 leftResult ++; 58 } 59 result += leftResult*rightResult; 60 left ++; 61 oneSum --; 62 } 63 } 64 return result; 65 } 66 };
以上是关于Leetcode-930 Binary Subarrays With Sum(和相同的二元子数组)的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 930 和相同的二元子数组[动态规划 前缀和] HERODING的LeetCode之路