【leetcode】1248. Count Number of Nice Subarrays

题目如下:

Given an array of integers nums and an integer k. A subarray is called nice if there are k odd numbers on it.

Return the number of nice sub-arrays.

Example 1:

Input: nums = [1,1,2,1,1], k = 3
Output: 2
Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].

Example 2:

Input: nums = [2,4,6], k = 1
Output: 0
Explanation: There is no odd numbers in the array.

Example 3:

Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2
Output: 16

Constraints:

  • 1 <= nums.length <= 50000
  • 1 <= nums[i] <= 10^5
  • 1 <= k <= nums.length

解题思路:创建一个val数组,val[i]表示从0~i区间内奇数的个数。如果要求i~j区间内奇数的个数,似乎只有val[j] - val[i]即可。但是还要再考虑一点,就是nums[i]的奇偶性。如果nums[i]是奇数,那么区间的奇数数量就是 val[j] - val[i] + 1;否则则为val[j] - val[i]。最后从头开始遍历val,对于每个val[i]来说,只要知道val[i] + k 或者val[i] + k - 1在val整个数组中出现的个数,即可求得nums以第i个元素为首的并且奇数个数为k的子数组的数量。

代码如下:

class Solution(object):
    def numberOfSubarrays(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        count = 0
        val = [0] * len(nums)
        dic = {}
        for i in range(len(nums)):
            if nums[i] % 2 == 1:count += 1
            val[i] = count
            dic[count] = dic.setdefault(count,0) + 1
        #print val

        res = 0

        for i in range(len(nums)):
            if nums[i]%2 == 0:
                key = val[i] + k
            else:
                key = val[i] + k -1
            if key in dic:
                res += dic[key]
        return res
原文地址:https://www.cnblogs.com/seyjs/p/11790708.html