九章算法 | 腾讯面试题:和相同的二元子数组

2021-02-20 12:02:30 +08:00
 hakunamatata11

描述

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

[在线评测地址](https://www.lintcode.com/problem/binary-subarrays-with-sum/?utm_source=sc-zhihuzl-sy)

样例 1

Input: A = [1,0,1,0,1], S = 2
Output: 4
Explanation: 
The 4 subarrays are bolded below:
[1,0,1]
[1,0,1]
[1,0,1,0]
[0,1,0,1]

样例 2

Input: A = [0,0,0,0,0,0,1,0,0,0], S = 0
Output: 27
Explanation: 
And 27 subarrays for S.

题解

前缀和:定义一个数组 sumN+1,si表示数组 A 中前 i 个元素之和,然后遍历 sum 数组,计算 si+S(含义:前 i 个元素之和是 si,找和为 S 的子数组个数)。求 si+S 的个数

public class Solution {
    /**
     * @param A: an array
     * @param S: the sum
     * @return: the number of non-empty subarrays
     */
    public int numSubarraysWithSum(int[] A, int S) {
        // Write your code here.
        if (A == null || A.length == 0) {
            return 0;
        }
        int prefixSum = 0;
        int res = 0;
        // counts[i] means the number of prefixSum = i
        int[] counts = new int[A.length + 1];
        counts[0] = 1;
        for (int i = 0; i < A.length; i++) {
            prefixSum += A[i];
            if (prefixSum >= S) {
                res += counts[prefixSum - S];
            }
            counts[prefixSum]++;
        }
        return res;
    }
}

[更多题解参考](https://www.jiuzhang.com/solution/binary-subarrays-with-sum/?utm_source=sc-zhihuzl-sy )

450 次点击
所在节点    推广
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/754546

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX