Leetcode 307. Range Sum Query - Mutable

Problem

Given an integer array nums, handle multiple queries of the following types:

  1. Update the value of an element in nums.
  2. Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.

Implement the NumArray class:

  • NumArray(int[] nums) Initializes the object with the integer array nums.
  • void update(int index, int val) Updates the value of nums[index] to be val.
  • int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + … + nums[right]).

Algorithm

Use a Fenwick Tree (Binary Indexed Tree) to store data and perform sum queries, allowing operations with a time complexity of log(n).

Code

class NumArray:

    def _lowbit(self, x: int) -> int:
        return x & -x

    def _add(self, i: int, delta: int):
        while i <= self.nlen:
            self.c[i] += delta
            i += self._lowbit(i)

    def _prefix_sum(self, i: int) -> int:
        res = 0
        while i > 0:
            res += self.c[i]
            i -= self._lowbit(i)
        return res

    def __init__(self, nums: List[int]):
        self.nlen = len(nums)
        self.nums = nums[:]
        self.c = [0] * (self.nlen + 1) 
        for i in range(self.nlen):
            self._add(i + 1, nums[i])  

    def update(self, index: int, val: int) -> None:
        delta = val - self.nums[index]
        self.nums[index] = val
        self._add(index + 1, delta)

    def sumRange(self, left: int, right: int) -> int:
        return self._prefix_sum(right + 1) - self._prefix_sum(left)

# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# obj.update(index,val)
# param_2 = obj.sumRange(left,right)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值