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)
}
相关推荐
灯澜忆梦7 分钟前
【基于GO的Web开发14】gin请求重定向
前端·后端·golang·gin
路多辛25 分钟前
为什么用 Go 写 AI Agent,covo-agent 的选型思考
开发语言·golang·agent·ai编程
Tisfy4 小时前
LeetCode 1927.求和游戏:抵消+看最值
java·leetcode·游戏·题解·博弈论
玖玥拾4 小时前
LeetCode 125 验证回文串
算法·leetcode
FfHUCisI10 小时前
Go 编译过程全景
开发语言·后端·golang
FfHUCisI10 小时前
Golang 语法分析与 AST:Parser 与 go/ast
开发语言·后端·golang
玖玥拾14 小时前
LeetCode 392 判断子序列
笔记·算法·leetcode
SLD_Allen14 小时前
Go语言runtime全景
开发语言·javascript·golang
重生之后端学习15 小时前
239. 滑动窗口最大值[困难]✅
java·数据结构·算法·leetcode·职场和发展
深念Y17 小时前
为什么选 Go:直观、可维护、AI 友好
linux·开发语言·人工智能·golang·agent·harness