Golang | Leetcode Golang题解之第327题区间和的个数

题目:

题解:

Go 复制代码
import "math/rand" // 默认导入的 rand 不是这个库,需要显式指明

type node struct {
    ch       [2]*node
    priority int
    key      int
    dupCnt   int
    sz       int
}

func (o *node) cmp(b int) int {
    switch {
    case b < o.key:
        return 0
    case b > o.key:
        return 1
    default:
        return -1
    }
}

func (o *node) size() int {
    if o != nil {
        return o.sz
    }
    return 0
}

func (o *node) maintain() {
    o.sz = o.dupCnt + o.ch[0].size() + o.ch[1].size()
}

func (o *node) rotate(d int) *node {
    x := o.ch[d^1]
    o.ch[d^1] = x.ch[d]
    x.ch[d] = o
    o.maintain()
    x.maintain()
    return x
}

type treap struct {
    root *node
}

func (t *treap) _insert(o *node, key int) *node {
    if o == nil {
        return &node{priority: rand.Int(), key: key, dupCnt: 1, sz: 1}
    }
    if d := o.cmp(key); d >= 0 {
        o.ch[d] = t._insert(o.ch[d], key)
        if o.ch[d].priority > o.priority {
            o = o.rotate(d ^ 1)
        }
    } else {
        o.dupCnt++
    }
    o.maintain()
    return o
}

func (t *treap) insert(key int) {
    t.root = t._insert(t.root, key)
}

// equal=false: 小于 key 的元素个数
// equal=true: 小于或等于 key 的元素个数
func (t *treap) rank(key int, equal bool) (cnt int) {
    for o := t.root; o != nil; {
        switch c := o.cmp(key); {
        case c == 0:
            o = o.ch[0]
        case c > 0:
            cnt += o.dupCnt + o.ch[0].size()
            o = o.ch[1]
        default:
            cnt += o.ch[0].size()
            if equal {
                cnt += o.dupCnt
            }
            return
        }
    }
    return
}

func countRangeSum(nums []int, lower, upper int) (cnt int) {
    preSum := make([]int, len(nums)+1)
    for i, v := range nums {
        preSum[i+1] = preSum[i] + v
    }

    t := &treap{}
    for _, sum := range preSum {
        left, right := sum-upper, sum-lower
        cnt += t.rank(right, true) - t.rank(left, false)
        t.insert(sum)
    }
    return
}
相关推荐
im_AMBER5 分钟前
Leetcode 103 反转链表 II
数据结构·c++·笔记·学习·算法·leetcode
Mr -老鬼1 小时前
Java、Go、Rust高并发时代“称雄”之战:场景适配与生态博弈
java·golang·rust
iAkuya1 小时前
(leetcode)力扣100 40二叉树的直径(迭代递归)
java·算法·leetcode
橘颂TA1 小时前
【剑斩OFFER】算法的暴力美学——leetCode 103 题:二叉树的锯齿形层序遍历
算法·leetcode·结构与算法
客卿1231 小时前
C语言实现数组串联--力扣冒险
c语言·开发语言·leetcode
Lips6112 小时前
2026.1.13力扣刷题笔记
笔记·算法·leetcode
老鼠只爱大米2 小时前
LeetCode算法题详解 76:最小覆盖子串
算法·leetcode·双指针·滑动窗口·最小覆盖子串·minwindow
源代码•宸2 小时前
Golang原理剖析(map)
经验分享·后端·算法·golang·哈希算法·散列表·map
wen__xvn2 小时前
代码随想录算法训练营DAY15第六章 二叉树part03
数据结构·算法·leetcode
Swift社区2 小时前
LeetCode 374 猜数字大小 - Swift 题解
算法·leetcode·swift