[力扣] 算法 930 (C++)

930. 和相同的二元子数组

class Solution {
public:
    int numSubarraysWithSum(vector<int>& nums, int goal) {
		vector map{ 1 };
		for (auto&& num : nums)
		{
			if (num)
			{
				map.emplace_back(1);
			}
			else
			{
				++map.back();
			}
		}
		int ret = 0;
		for (unsigned i = goal; i < map.size(); ++i)
		{
			if (goal > 0)
			{
				ret += map[i] * map[i - goal];
			}
			else
			{
				ret += map[i] * (map[i] - 1) / 2;
			}
		}
		return ret;
    }
};

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据