Python 程序:查找每个大小为 K 的窗口都包含唯一元素的数字列表
假设我们有一个名为 nums 的数字列表和另一个数字 k,我们需要找到一个列表,其中包含每个大小为 k 的窗口中不同数字的数量。
因此,如果输入类似于 nums = [2, 2, 3, 3, 4],k = 2,则输出将为 [1, 2, 1, 2],因为窗口为 [2, 2]、[2, 3]、[3, 3] 和 [3, 4]。
为了解决这个问题,我们将遵循以下步骤:
c := 创建一个字典,存储 nums 中元素及其频率。
ans := 新建一个列表。
对于 i 从 k 到 nums 的大小范围,执行以下操作:
将 c 的大小插入 ans 的末尾。
c[nums[i]] := c[nums[i]] + 1
c[nums[i - k]] := c[nums[i - k]] - 1
如果 c[nums[i - k]] 等于 0,则:
删除 c[nums[i - k]]。
将 c 的大小插入 ans 的末尾。
返回 ans。
让我们看看下面的实现,以便更好地理解:
示例
from collections import Counter class Solution: def solve(self, nums, k): c = Counter() for i in range(k): c[nums[i]] += 1 ans = [] for i in range(k, len(nums)): ans.append(len(c)) c[nums[i]] += 1 c[nums[i - k]] -= 1 if c[nums[i - k]] == 0: del c[nums[i - k]] ans.append(len(c)) return ans ob = Solution() nums = [2, 2, 3, 3, 4] print(ob.solve(nums, 2))
输入
[2, 2, 3, 3, 4], 2
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
[1, 2, 1, 2]
广告