LeetCode307 Range Sum Query-Mutable

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

Given an integer array nums, find the sum of the elements between indices i and j (ij), inclusive.

The update(i, val) function modifies nums by updating the element at index i to val.

Note:

  1. The array is only modifiable by the update function.
  2. You may assume the number of calls to update and sumRange function is distributed evenly.

样例

1
2
3
4
5
Given nums = [1, 3, 5]

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

思路

要求对数组支持单点修改,区间查询操作。

树状数组 模板题,修改、查询复杂度都是$\mathcal{O}(logn)$。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class NumArray {
private:
int* sum;
int n;
public:
int lowbit(int x) {
return x & -x;
}
void add(int i, int x) {
while (i <= n) {
sum[i] += x;
i += lowbit(i);
}
}
int getSum(int i) {
int ans = 0;
while (i > 0) {
ans += sum[i];
i -= lowbit(i);
}
return ans;
}
NumArray(vector<int> nums) {
n = nums.size();
sum = new int[n + 1];
fill(sum, sum + n + 1, 0);
for (int i = 0; i < n; ++i) {
add(i + 1, nums[i]);
}
}
void update(int i, int val) {
add(i + 1, val - sumRange(i, i));
}
int sumRange(int i, int j) {
return getSum(j + 1) - getSum(i);
}
};

/*
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* obj.update(i,val);
* int param_2 = obj.sumRange(i,j);
*/
分享到 评论