307 Range Sum Query - Mutable
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
The update(i, val) function modifies nums by updating the element at index i to val.
Example:
Constraints:
The array is only modifiable by the update function.
You may assume the number of calls to update and sumRange function is distributed evenly.
0 <= i <= j <= nums.length - 1
嘛,这题因为很多update所以不能再用纯数组类型的prefix sum了。这里可以用BIT或者Segment Tree。
先学了BIT。其实这题是一个很直白的implementation。虽然说是树,但其实存的时候是数组,root是tree[0],val也是0,其他的node分别对应一截sum,有长有短。然后parent的关系是这个index - (index & -index),好像就是去掉最低位的1。每次更新的时候,我们也要更新后面所有位置的prefix sum,然后需要更新的位置index + (index & -index)。每次求0到现在index的前序和,就把这个节点一直往上加到root
看了答案,发现其实不需要用numsCopy来存旧的数是多少,因为我们可以通过求sumRange(updateIndex, updateIndex)来求出这个数原来值是多少
Time Complexity
Update (1D) - O(logN)
Query (1D) - O(logN)
Build (1D) - O(N⋅logN)
Here N denotes the number of elements present in the array. Maximum number of steps that we'll have to iterate for update and query method is upper bounded by the number of bits in the binary representation of the size of the array (N).
Space Complexity
O(N)
Last updated