Golang | Leetcode Golang题解之第307题区域和检索-数组可修改

题目:

题解:

Go 复制代码
type NumArray struct {
    nums, tree []int
}

func Constructor(nums []int) NumArray {
    tree := make([]int, len(nums)+1)
    na := NumArray{nums, tree}
    for i, num := range nums {
        na.add(i+1, num)
    }
    return na
}

func (na *NumArray) add(index, val int) {
    for ; index < len(na.tree); index += index & -index {
        na.tree[index] += val
    }
}

func (na *NumArray) prefixSum(index int) (sum int) {
    for ; index > 0; index &= index - 1 {
        sum += na.tree[index]
    }
    return
}

func (na *NumArray) Update(index, val int) {
    na.add(index+1, val-na.nums[index])
    na.nums[index] = val
}

func (na *NumArray) SumRange(left, right int) int {
    return na.prefixSum(right+1) - na.prefixSum(left)
}
相关推荐
codeejun1 天前
每日一Go·MySQL-22、幻读、不可重复读、脏读实战演示
开发语言·mysql·golang
码途行者1 天前
每天10分钟学Go:第17课 接口interface-只规定“能做什么“,不管它是什么
开发语言·后端·golang
利威尔xu2 天前
2026-11-24-Go限流器实战
后端·golang
Navigator_Z2 天前
LeetCode //C - 1320. Minimum Distance to Type a Word Using Two Fingers
c语言·算法·leetcode
码途行者2 天前
每天10分钟学Go:第21课 错误
开发语言·后端·golang
码途行者2 天前
每天10分钟学Go:第22课 自定义错误
开发语言·后端·golang
wy_hhxx3 天前
[Leetcode] 滑动窗口
算法·leetcode·滑动窗口
码途行者3 天前
每天10分钟学Go:第20课 泛型
c++·算法·golang
codeejun3 天前
每日一Go·MySQL-20、SQL 性能调优实战总结
sql·mysql·golang
AIgorithmGEEK3 天前
算法·哈希表|从“逐个比”到“按 key 算位置”
数据结构·c++·算法·leetcode·hash