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)
}
相关推荐
Allen_LVyingbo11 分钟前
构建医疗AI数据集建设平台:Go语言工程方案详解
开发语言·人工智能·自然语言处理·golang·知识图谱·健康医疗
程序员-King.18 分钟前
day150—数组—二叉树的锯齿形层序遍历(LeetCode-103)
算法·leetcode·二叉树
sin_hielo19 分钟前
leetcode 3314(位运算,lowbit)
数据结构·算法·leetcode
Remember_99319 分钟前
【数据结构】深入理解排序算法:从基础原理到高级应用
java·开发语言·数据结构·算法·spring·leetcode·排序算法
bybitq20 分钟前
Leetcode-124-二叉树最大路径和-Python
算法·leetcode·深度优先
AlenTech21 分钟前
1683. 无效的推文 - 力扣(LeetCode)
leetcode
鱼跃鹰飞23 分钟前
Leetcode会员专享题:426.将二叉搜索树转换为排序的双向链表
数据结构·算法·leetcode·链表·深度优先
漫随流水24 分钟前
leetcode回溯算法(39.组合总和)
数据结构·算法·leetcode·回溯算法
苦藤新鸡30 分钟前
20.右旋转图片
数据结构·算法·leetcode·力扣
月挽清风35 分钟前
代码随想录第六天:哈希表
算法·leetcode