分段树算法 (leetcode 307 python)

 

题目:给定一个整数数组  nums,求出数组从索引 到 j  (i ≤ j) 范围内元素的总和,包含 i,  j 两点。

update(i, val) 函数可以通过将下标为 的数值更新为 val,从而对数列进行修改。

示例:

Given nums = [1, 3, 5]

sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8

说明:

  1. 数组仅可以在 update 函数下进行修改。
  2. 你可以假设 update 函数与 sumRange 函数的调用次数是均匀分布的。
__author__ = "那位先生Beer"


class NumArray( object ):
    def __init__( self, nums ):
        self.l = len( nums )
        self.nums = [0] * self.l
        for i in nums:
            self.nums.append( i )
        i = self.l - 1
        while (i > 0):
            self.nums[i] = self.nums[2 * i] + self.nums[2 * i + 1]
            i -= 1

    def update( self, i, val ):
        i += self.l
        diff = val - self.nums[i]
        while (i > 0):
            self.nums[i] += diff
            i //= 2

    def sumRange( self, i, j ):
        sum = 0
        i += self.l
        j += self.l
        while (i <= j):
            if i % 2 == 1:
                sum += self.nums[i]
                i += 1
            if j % 2 == 0:
                sum += self.nums[j]
                j -= 1
            i = i // 2
            j = j // 2
        return sum




# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# obj.update(i,val)
# param_2 = obj.sumRange(i,j)

  

  

转载于:https://www.cnblogs.com/qkqBeer/articles/10178064.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值