【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.spa

Return the number of nice sub-arrays.code

Example 1:blog

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:it

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

Example 3:io

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

Constraints:class

  • 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的子數組的數量。object

代碼以下:List

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
相關文章
相關標籤/搜索