Binary Subarrays With Sum
阿新 • • 發佈:2018-12-25
In an array A
of 0
s and 1
s, how many non-empty subarrays have sum S
?
Example 1:
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 either0
or1
.
題目理解:
給定一個01陣列,和一個指定數S,求出有多少個子陣列的和是S
解題思路:
找到以1開始並且以1結尾,並且和為S的子串,然後計算這個子串的左邊有多少個0,右邊有多少個0,相乘再相加。
因為元素只有0和1,所以找子串的過程可以是線性的,每次放棄最左邊的1,並且在最右邊新增一個1就行
程式碼如下:
class Solution { public int numSubarraysWithSum(int[] A, int S) { if(S == 0){ int count = 0, res = 0; for(int i : A){ if(i == 1){ res += count * (count + 1) / 2; count = 0; } else count++; } res += count * (count + 1) / 2; return res; } int sum = 0; int left = 0, right = 0; int len = A.length; int res = 0; while(right < len){ while(right < len && sum < S){ sum += A[right++]; } if(right == len && sum < S) break; int front = 1, back = 1; while(left < right && A[left] == 0){ front++; left++; } while(right < len && A[right] == 0){ back++; right++; } sum -= A[left++]; res += front * back; } return res; } }