窗口大小为3的整数列表滑动求和类实现问题求助
滑动窗口求和问题解决方案
问题背景
需要实现一个支持滑动窗口求和的类,核心要求:
- 窗口大小默认3,可配置
- 接收分批传入的整数列表,按顺序累积数字
- 每凑够窗口大小的连续数字,计算其和并永久记录
- 未凑够窗口大小的累积和需动态更新,允许查询当前的累积状态
- 提供方法检查某个和是否已被记录(包括永久记录的完整窗口和、当前未完成的累积和)
现有代码问题
你提供的代码无法正确维护未完成的累积状态:
- 未保留上一次push后的剩余累积值,每次push都会重新开始计算total
- 仅在凑够窗口大小时才记录和,忽略了未完成的累积和的记录需求
- 无法动态更新未完成的累积和,导致查询时无法返回正确结果
修正后的代码
from typing import List class MovingSum: def __init__(self, window=3): self.window = window # 存储所有已完成的窗口和(永久保留) self.completed_totals = set() # 当前未完成的累积和 self.pending_sum = 0 # 当前未完成的数字个数 self.pending_count = 0 def push(self, nums: List[int]): for num in nums: self.pending_sum += num self.pending_count += 1 # 凑够窗口大小,记录完整和并重置累积状态 if self.pending_count == self.window: self.completed_totals.add(self.pending_sum) self.pending_sum = 0 self.pending_count = 0 def belongs(self, total) -> bool: # 检查是否是已完成的窗口和,或是当前未完成的累积和 if total in self.completed_totals: return True return self.pending_count > 0 and self.pending_sum == total
功能验证
按照你提供的示例流程验证:
初始调用
push([1,2,3,4]):- 完成窗口和:1+2+3=6(加入
completed_totals) - 未完成累积:4(
pending_sum=4,pending_count=1) - 调用
belongs(6)→True,belongs(4)→True
- 完成窗口和:1+2+3=6(加入
调用
push([10]):- 未完成累积更新:4+10=14(
pending_sum=14,pending_count=2) - 调用
belongs(6)→True,belongs(14)→True
- 未完成累积更新:4+10=14(
调用
push([20]):- 累积和:14+20=34,凑够3个数字,加入
completed_totals - 重置累积状态(
pending_sum=0,pending_count=0) - 调用
belongs(6)→True,belongs(34)→True
- 累积和:14+20=34,凑够3个数字,加入
调用
push([10,20,30]):- 完成窗口和:10+20+30=60(加入
completed_totals) - 累积状态重置
- 调用
belongs(6)→True,belongs(34)→True,belongs(60)→True
- 完成窗口和:10+20+30=60(加入
针对你提供的测试用例(注:测试用例中若要匹配“20+40=60达窗口大小”的描述,需初始化时传入window=2),执行流程后所有belongs查询均会返回正确结果。
内容的提问来源于stack exchange,提问作者turtle_in_mind
相关产品推荐
相关产品推荐

