用 Python 编写程序,查找每个 K 大小窗口都有唯一元素的数字列表

pythonserver side programmingprogramming更新于 2026/1/17 6:36:17

假设我们有一个名为 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 := 一个新列表

  • for i in range k to size of nums,do

    • 在 ans 末尾插入 c 的大小

    • 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]]

  • 在 ans 末尾插入 c 的大小

  • 返回 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

输出

[1, 2, 1, 2]

相关文章


有用资源