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
}
相关推荐
এ᭄画画的北北1 小时前
力扣-160.相交链表
算法·leetcode·链表
唐僧洗头爱飘柔95274 小时前
(Go Gin)上手Go Gin 基于Go语言开发的Web框架,本文介绍了各种路由的配置信息;包含各场景下请求参数的基本传入接收
后端·golang·go·restful·gin·goweb开发
mit6.8244 小时前
[贪心_7] 最优除法 | 跳跃游戏 II | 加油站
数据结构·算法·leetcode
凯子坚持 c7 小时前
深度解析之算法之分治(快排)
算法·leetcode·职场和发展
石去皿12 小时前
力扣hot100 91-100记录
算法·leetcode·职场和发展
圣保罗的大教堂14 小时前
leetcode 2799. 统计完全子数组的数目 中等
leetcode
SsummerC14 小时前
【leetcode100】组合总和Ⅳ
数据结构·python·算法·leetcode·动态规划
YuCaiH14 小时前
数组理论基础
笔记·leetcode·c·数组
2301_8076114914 小时前
77. 组合
c++·算法·leetcode·深度优先·回溯
SsummerC16 小时前
【leetcode100】零钱兑换Ⅱ
数据结构·python·算法·leetcode·动态规划