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)
}
相关推荐
坚持编程的菜鸟2 分钟前
LeetCode每日一题——螺旋矩阵
c语言·算法·leetcode·矩阵
(●—●)橘子……9 分钟前
记力扣2009:使数组连续的最少操作数 练习理解
数据结构·python·算法·leetcode
GalaxyPokemon12 分钟前
LeetCode - 1171.
算法·leetcode·链表
iナナ40 分钟前
Java优选算法——位运算
java·数据结构·算法·leetcode
Han.miracle2 小时前
数据结构二叉树——层序遍历&& 扩展二叉树的左视图
java·数据结构·算法·leetcode
L_09074 小时前
【Algorithm】Day-4
c++·算法·leetcode
代码充电宝4 小时前
LeetCode 算法题【简单】20. 有效的括号
java·算法·leetcode·面试·职场和发展
海琴烟Sunshine5 小时前
leetcode 119. 杨辉三角 II python
算法·leetcode·职场和发展
玉夏6 小时前
【每日算法C#】爬楼梯问题 LeetCode
算法·leetcode·c#
Excuse_lighttime7 小时前
只出现一次的数字(位运算算法)
java·数据结构·算法·leetcode·eclipse