LeetCode303 Range Sum Query-Immutable

文章目录
  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.

Note:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.

样例

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

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

思路

查询数组的区间和。

其中数组元素不会改变,会有频繁的查询操作。

$\mathcal{O}(n)$预处理出前缀和,然后$\mathcal{O}(1)$查询即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class NumArray {
private:
int* sum;
public:
NumArray(vector<int> nums) {
int n = nums.size();
sum = new int[n + 1];
sum[0] = 0;
for (int i = 1; i <= n; ++i) {
sum[i] = sum[i-1] + nums[i-1];
}
}

int sumRange(int i, int j) {
return sum[j + 1] - sum[i];
}
};

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