leetcode 2916. 子数组不同元素数目的平方和 II(区间更新 + 区间查询 线段树第二个板子 双闭区间 避开0)

描述

偷了一个线段树板子

不知道为啥要避开0

然后这里的更新和查找都是用双闭区间的

ac code

python 复制代码
class SegmentTree:
    def __init__(self, n):
        self.n = n 
        self.B1 = [0]*n 
        self.B2 = [0]*n  


    def add(self, b, idx, x):
        N = self.n 
        while idx < N:
            b[idx] += x
            idx += idx & -idx

    def range_add(self, l,r,x):
        B1 = self.B1
        B2 = self.B2
        self.add(B1, l, x)
        self.add(B1, r+1, -x)
        self.add(B2, l, x*(l-1))
        self.add(B2, r+1, -x*r)

    def sum(self, b, idx):
        total = 0
        while idx > 0:
            total += b[idx]
            idx -= idx & -idx
        return total

    def prefix_sum(self, idx):
        B1 = self.B1
        B2 = self.B2
        return self.sum(B1, idx)*idx -  self.sum(B2, idx)

    def range_sum(self, l, r):
        return self.prefix_sum(r) - self.prefix_sum(l-1)

class Solution:
    def sumCounts(self, nums: List[int]) -> int:
        n = len(nums)
        seg = SegmentTree(n+5)
        MOD = 10**9+7
        seen = dict()
        ans, cur = 0, 0 
        for i, a in enumerate(nums):
            j = -1 if a not in seen else seen[a]
            s = seg.range_sum(j+2,i+1) # 双闭区间
            cur += s*2+i-j
            cur %= MOD 
            ans += cur
            ans %= MOD
            # print(i,s,cur)
            seg.range_add(j+2,i+1,1)
            seen[a] = i
        return ans

题目链接

lc2916

相关推荐
Swift社区10 小时前
LeetCode 394. 字符串解码(Decode String)
算法·leetcode·职场和发展
tt55555555555511 小时前
LeetCode进阶算法题解详解
算法·leetcode·职场和发展
让我们一起加油好吗11 小时前
【基础算法】DFS中的剪枝与优化
算法·深度优先·剪枝
Q741_14711 小时前
C++ 模拟题 力扣495. 提莫攻击 题解 每日一题
c++·算法·leetcode·模拟
我命由我1234512 小时前
Excel - Excel 列出一列中所有不重复数据
经验分享·学习·职场和发展·word·powerpoint·excel·职场发展
Felven12 小时前
A. Be Positive
算法
小O的算法实验室12 小时前
2026年COR SCI2区,自适应K-means和强化学习RL算法+有效疫苗分配问题,深度解析+性能实测,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
青岛少儿编程-王老师13 小时前
CCF编程能力等级认证GESP—C++7级—20250927
数据结构·c++·算法
夏鹏今天学习了吗13 小时前
【LeetCode热题100(39/100)】对称二叉树
算法·leetcode·职场和发展
天选之女wow14 小时前
【代码随想录算法训练营——Day34】动态规划——416.分割等和子集
算法·leetcode·动态规划