其他分享
首页 > 其他分享> > leetcode-161周赛-5248-统计【优美子数组】

leetcode-161周赛-5248-统计【优美子数组】

作者:互联网

题目描述:

 

 

 自己的提交:超时:

class Solution:
    def numberOfSubarrays(self, nums, k: int) -> int:
        dp = [0]* (len(nums)+1)
        res = 0
        for i in range(len(nums)):
            if nums[i] % 2 == 0:
                dp[i+1] = dp[i]
            else:
                dp[i+1] = dp[i] + 1
            if dp[i+1] == k:
                res += 1
        for i in range(len(nums)):
            for j in range(len(nums)+1):
                if nums[i] % 2 == 1:
                    dp[j] -= 1
                if dp[j] == k:
                    res += 1
        return res

参考后提交:O(N)

class Solution:
    def numberOfSubarrays(self, nums, k: int) -> int:
        dp = [0]* (len(nums)+1)
        res = 0
        for i in range(len(nums)):
            if nums[i] % 2 == 0:
                dp[i+1] = dp[i]
            else:
                dp[i+1] = dp[i] + 1
        from collections import Counter
        dic = Counter(dp)
        for i in dp:
            if i >= k:
                res += dic[i-k]
        return res
                

优化:

import collections
class Solution:
    def numberOfSubarrays(self, nums, k: int) -> int:
        mp = collections.Counter()
        mp[0] = 1
        g = 0
        ans = 0
        for num in nums:
            if num % 2 == 1:
                g += 1
            ans += mp[g - k]
            mp[g] += 1
        return ans

 

标签:周赛,5248,nums,int,res,len,mp,161,dp
来源: https://www.cnblogs.com/oldby/p/11791714.html