[力扣] 算法 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;
    }
};

发表评论