LC.P303[区域和检索-数组不可变]

方法一:前缀和

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class NumArray {

int[] sum;

public NumArray(int[] nums) {
int n = nums.length;
sum = new int[n + 1];
for (int i = 1; i <= n; ++i) {
sum[i] = sum[i - 1] + nums[i - 1];
}
}

public int sumRange(int left, int right) {
return sum[right + 1] - sum[left];
}
}

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