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)
}
相关推荐
geovindu1 小时前
go:loghelper
开发语言·后端·golang
海绵天哥3 小时前
LeetCode Hot 100 | 链表(下)· 分组翻转与设计(C++ 题解)
c++·leetcode·链表
会编程的土豆4 小时前
GoWeb 处理请求详解:请求行、请求头、请求参数与给客户端响应
开发语言·http·golang
tkevinjd18 小时前
力扣131-分割回文串
算法·leetcode·深度优先
zander25821 小时前
LeetCode 78. 子集
算法·leetcode·深度优先
Tisfy1 天前
LeetCode 3014.输入单词需要的最少按键次数 I:遍历 / if-else计算(比纯数学公式写起来麻烦但好想)
数学·算法·leetcode·字符串·题解·贪心
tkevinjd1 天前
力扣239-滑动窗口最大值
算法·leetcode·职场和发展
圣保罗的大教堂1 天前
leetcode 628. 三个数的最大乘积 简单
leetcode
良木林1 天前
矩阵 - LeetCode hot 100
线性代数·算法·leetcode·矩阵
北冥you鱼1 天前
Go语言 sql.Null 类型详解:处理数据库 NULL 值的正确姿势
数据库·sql·golang