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)
}
相关推荐
一叶落4382 小时前
题目:15. 三数之和
c语言·数据结构·算法·leetcode
呆萌很2 小时前
【GO】切片练习题
golang
big_rabbit05024 小时前
[算法][力扣222]完全二叉树的节点个数
数据结构·算法·leetcode
张李浩4 小时前
Leetcode 15三题之和
算法·leetcode·职场和发展
x_xbx5 小时前
LeetCode:206. 反转链表
算法·leetcode·链表
abant25 小时前
leetcode 138 复制随机链表
算法·leetcode·链表
做怪小疯子7 小时前
Leetcode刷题——8.重叠区间
算法·leetcode·职场和发展
_饭团8 小时前
指针核心知识:5篇系统梳理3
c语言·数据结构·算法·leetcode·面试·学习方法·改行学it
呆萌很8 小时前
【GO】数组练习题
golang
阿Y加油吧8 小时前
力扣打卡——day01
java·算法·leetcode