随意想到的算法题整理

和为某个值的连续子序列个数

利用区间的减法:
[b, c] = [a, c] - [a, b]

在这里插入图片描述

def count_sublists_with_sum(lst, target_sum):
    count = 0
    cum_sum = {0: 1}  # 从0开始,表示空子列表的和为0
    current_sum = 0

    for num in lst:
        current_sum += num
        # 如果(current_sum - target_sum)已经在字典中,说明存在子列表和为目标值
        if (current_sum - target_sum) in cum_sum:
            count += cum_sum[current_sum - target_sum]
        # 如果当前元素的累积和不在字典中,添加进去
        if current_sum not in cum_sum:
            cum_sum[current_sum] = 1
        else:
            # 如果已经在字典中,增加出现的次数
            cum_sum[current_sum] += 1

    return count

# 示例使用
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target = 9
print(count_sublists_with_sum(my_list, target))  # 输出满足条件的子列表个数
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值