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)
}
相关推荐
Two_brushes.2 小时前
【算法】宽度优先遍历BFS
算法·leetcode·哈希算法·宽度优先
凌肖战13 小时前
力扣网编程55题:跳跃游戏之逆向思维
算法·leetcode
黑听人13 小时前
【力扣 简单 C】70. 爬楼梯
c语言·leetcode
ゞ 正在缓冲99%…14 小时前
leetcode918.环形子数组的最大和
数据结构·算法·leetcode·动态规划
Kaltistss15 小时前
98.验证二叉搜索树
算法·leetcode·职场和发展
程序员爱钓鱼15 小时前
Go语言项目工程化 — 常见开发工具与 CI/CD 支持
开发语言·后端·golang·gin
许愿与你永世安宁21 小时前
力扣343 整数拆分
数据结构·算法·leetcode
爱coding的橙子21 小时前
每日算法刷题Day42 7.5:leetcode前缀和3道题,用时2h
算法·leetcode·职场和发展
YuTaoShao1 天前
【LeetCode 热题 100】73. 矩阵置零——(解法二)空间复杂度 O(1)
java·算法·leetcode·矩阵
杰克尼1 天前
1. 两数之和 (leetcode)
数据结构·算法·leetcode