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)
}
相关推荐
speop1 天前
llm-algo-leetcode |Task01
算法·leetcode·职场和发展
Scabbards_1 天前
面试Leetcode - 算法合集
算法·leetcode·面试
程序猿炎义1 天前
【llm-algo-leetcode学习笔记】显存与性能认知底座
笔记·学习·leetcode
rannn_1111 天前
【力扣hot100】二叉树专题+总结
java·算法·leetcode·二叉树
啊嘞嘞?1 天前
力扣(岛屿数量)
算法·leetcode
zander2581 天前
LeetCode 198. 打家劫舍
算法·leetcode·深度优先
吃着火锅x唱着歌1 天前
LeetCode 648.单词替换
算法·leetcode·职场和发展
Elsa️7461 天前
leetcode 14.最长公共前缀
算法·leetcode·职场和发展
灯澜忆梦1 天前
【基于GO的Web开发3】gin框架_HTML渲染
前端·golang·gin
203号居民2 天前
LeetCode hot 100 —41. 缺失的第一个正数
数据结构·算法·leetcode