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

相关推荐
孤飞26 分钟前
zero2Agent:面向大厂面试的 Agent 工程教程,从概念到生产的完整学习路线
算法
zjeweler1 小时前
“网安+护网”终极300多问题面试笔记-3共3-综合题型(最多)
笔记·网络安全·面试·职场和发展·护网行动
技术专家2 小时前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
Hacker_Nightrain2 小时前
详解Selenium 和Playwright两大框架的不同之处
自动化测试·软件测试·selenium·测试工具·职场和发展
csdn_aspnet2 小时前
C# (QuickSort using Random Pivoting)使用随机枢轴的快速排序
数据结构·算法·c#·排序算法
鹿角片ljp2 小时前
最长回文子串(LeetCode 5)详解
算法·leetcode·职场和发展
paeamecium4 小时前
【PAT甲级真题】- Cars on Campus (30)
数据结构·c++·算法·pat考试·pat
chh5634 小时前
C++--模版初阶
c语言·开发语言·c++·学习·算法
RTC老炮5 小时前
带宽估计算法(gcc++)架构设计及优化
网络·算法·webrtc
dsyyyyy11015 小时前
计数孤岛(DFS和BFS解决)
算法·深度优先·宽度优先