LeetCode 992. Subarrays with K Different Integers 滑动窗口 at most

231 篇文章 0 订阅
该博客介绍了如何利用滑动窗口和字典数据结构解决一个编程问题,即给定一个整数数组,找出包含恰好k个不同整数的子数组数量。通过维护一个字典来跟踪子数组内的元素及其出现次数,博主展示了如何计算满足条件的子数组个数。示例代码中展示了对于不同输入的解决方案,例如输入数组[1,2,1,2,3]和k=2时,返回7个符合条件的子数组。
摘要由CSDN通过智能技术生成

Given an array nums of positive integers, call a (contiguous, not necessarily distinct) subarray of nums good if the number of different integers in that subarray is exactly k.

(For example, [1,2,3,1,2] has 3 different integers: 12, and 3.)

Return the number of good subarrays of nums.

Example 1:

Input: nums = [1,2,1,2,3], k = 2
Output: 7
Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].

Example 2:

Input: nums = [1,2,1,3,4], k = 3
Output: 3
Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].

Note:

  1. 1 <= nums.length <= 20000
  2. 1 <= nums[i] <= nums.length
  3. 1 <= k <= nums.length

------------------

直接滑动不太容易,用at_most数组辅助一下:

from typing import List

from collections import defaultdict
class Solution:
    def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:
        def at_most(nums, k):
            l, i, j, res = len(nums), 0, 0, 0
            dic = defaultdict(int)
            while (j < l):
                dic[nums[j]] += 1
                j += 1

                while (len(dic) > k and i < j):
                    dic[nums[i]] -= 1
                    if (dic[nums[i]] == 0):
                        dic.pop(nums[i])
                    i += 1
                #统计[i,j)范围内,也就是左闭区间,右开区间数的个数
                res = res + (j - i)
            return res
        return at_most(nums, k) - at_most(nums, k-1)

s = Solution()
print(s.subarraysWithKDistinct(nums = [1,2], k = 1))
print(s.subarraysWithKDistinct(nums = [1,2,1,2,3], k = 2))
print(s.subarraysWithKDistinct(nums = [1,2,1,3,4], k = 3))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值