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

相关推荐
开源Z25 分钟前
LeetCode 42 · 接雨水:从暴力到双指针的三步优化
算法·leetcode
旖-旎34 分钟前
《LeetCode 695 岛屿的最大面积 FloodFill DFS 解法》
c++·算法·力扣·深度优先遍历·floodfill
syagain_zsx1 小时前
STL 之 vector 讲练结合
c++·算法
MartinYeung53 小时前
[论文学习]DP2Unlearning:高效且具保证的大型语言模型遗忘框架(基于差分隐私的 LLM Unlearning 方法)
学习·算法·语言模型
Tian_Hang3 小时前
C++原型模式(Protype)
开发语言·c++·算法
bIo7lyA8v3 小时前
算法复杂度的渐进分析与实际运行时间的差异的技术8
算法
yuan199974 小时前
欧拉梁静力与屈曲计算的 MATLAB 实现(有限差分法 + 解析解)
开发语言·算法·matlab
汉克老师5 小时前
GESP7级C++考试语法知识(二、指数函数(3、综合练习)
c++·算法·数学建模·指数函数·gesp7级·复利
Seraphina_Lily5 小时前
深入C语言底层:隐式类型转换、整数提升与截断的“致命”陷阱
c语言·开发语言·算法