欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > Golang | Leetcode Golang题解之第327题区间和的个数

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

2024/10/24 13:22:41 来源:https://blog.csdn.net/weixin_66442839/article/details/140970825  浏览:    关键词:Golang | Leetcode Golang题解之第327题区间和的个数

题目:

题解:

import "math/rand" // 默认导入的 rand 不是这个库,需要显式指明type node struct {ch       [2]*nodepriority intkey      intdupCnt   intsz       int
}func (o *node) cmp(b int) int {switch {case b < o.key:return 0case b > o.key:return 1default: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] = oo.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-lowercnt += t.rank(right, true) - t.rank(left, false)t.insert(sum)}return
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com