Q:
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:
Given nums = [1, 3, 5]
sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8
Note:
The array is only modifiable by the update function.
You may assume the number of calls to update and sumRange function is distributed evenly.
题意大致是,给你提供一个二维数组,然后求指定下标之间的数之和,已知数组中的值可以更新,并且更新和求和操作会被频繁调用
Solution;
最原始的想法就是暴力遍历求和,不过想也不用想,当求和操作操作频繁调用,会超出给定时限。
并且,数组中的值会被频繁更新,我了解到的解决方法有Segement Tree(线段树),Binary Indexed Tree(树状数组) ,和平方根分解三种办法。树状数组真的是神作,很精巧的办法,也很高兴能够了解并学习这些数据结构。
想了解这道题Segement Tree(线段树)解法的可以参考这篇博客:
(LeetCode 307) Range Sum Query - Mutable(Segment Tree)
本篇博客提供树状数组的解释以及解法:
树状数组对于求元素值可变数组指定下标之间值之和的问题十分适合,当然也可应用在求最大值或者最小值这类的问题中。
如果不需要了解树状数组,可以直接翻到最后,会有AC源码。
要了解树状数组,我们先看它的存储形式:
图片来源:树状数组
我们可以看到当 i 为奇数时,
举个例子:
- 当 i=4 时,