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)
}
相关推荐
白中白121381 小时前
算法题-14
数据结构·算法·leetcode
王老师青少年编程1 小时前
2022年信奥赛C++提高组csp-s初赛真题及答案解析(完善程序第2题)
c++·题解·真题·初赛·信奥赛·csp-s·提高组
大黄说说2 小时前
彻底删除重复节点——LeetCode 82 题「有序链表去重 II」详解
算法·leetcode·链表
Hag_202 小时前
LeetCode Hot100 15.三数之和
算法·leetcode·职场和发展
菜鸡儿齐3 小时前
leetcode-移动零
数据结构·算法·leetcode
TracyCoder1233 小时前
LeetCode Hot100(53/100)——739. 每日温度
算法·leetcode·职场和发展
努力学算法的蒟蒻3 小时前
day84(2.13)——leetcode面试经典150
算法·leetcode·面试
@––––––3 小时前
力扣hot100—系列8-回溯算法
javascript·算法·leetcode
im_AMBER4 小时前
Leetcode 120 求根节点到叶节点数字之和 | 完全二叉树的节点个数
数据结构·学习·算法·leetcode·二叉树·深度优先
TracyCoder1234 小时前
LeetCode Hot100(54/100)——215. 数组中的第K个最大元素
算法·leetcode·排序算法