[leetcode]和相同的二元子数组

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014286840/article/details/84350179

930. 和相同的二元子数组

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

输入: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]

提示:

  1. A.length <= 30000
  2. 0 <= S <= A.length
  3. A[i] 为 0 或 1

C++解法:

class Solution {
public:
    int numSubarraysWithSum(vector<int>& A, int S) {
        int count = 0;
        for (size_t i = 0; i < A.size(); i++)
        {
            int sum = 0;
            bool flag = true;
            for (size_t j = i; j < A.size(); j++)
            {
                sum += A[j];
                if (flag)
                {
                    if (sum == S)
                    {
                        ++count;
                        flag = false;
                    }
                }
                else
                {
                    if (sum == S)
                    {
                        ++count;
                    }
                    else
                    {
                        break;
                    }
                }

            }
            if (sum < S)
            {
                break;
            }
        }
        return count;
    }
};

猜你喜欢

转载自blog.csdn.net/u014286840/article/details/84350179