LC.P307[区域和检索-数组可修改]

方法一:树状数组

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
45
46
47
48
49
class NumArray {

int[] tree;
int[] nums;
int n;

private int lowbit(int x) {
return x & -x;
}

private void add(int x, int val) {
for (int i = x; i <= n; i += lowbit(i)) {
tree[i] += val;
}
}

private int query(int x) {
int ans = 0;
for (int i = x; i > 0; i -= lowbit(i)) {
ans += tree[i];
}
return ans;
}

public NumArray(int[] nums) {
this.nums = nums;
this.n = nums.length;
this.tree = new int[n + 1];
for (int i = 0; i < n; ++i) {
add(i + 1, nums[i]);
}
}

public void update(int index, int val) {
add(index + 1, val - nums[index]);
nums[index] = val;
}

public int sumRange(int left, int right) {
return query(right + 1) - query(left);
}
}

/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* obj.update(index,val);
* int param_2 = obj.sumRange(left,right);
*/
  • 时间复杂度:$O(nlogn)$
  • 空间复杂度:$O(n)$