题意:给出数组num,求下标i到j的数组的和。
题解:前缀和搞,sum[i]表示0到i的前缀和。那么i到j的和就等于sum[j] - sum[i - 1].
class NumArray {
public:
vector<int> sum;
NumArray(vector<int> &nums) {
int n = nums.size();
sum.push_back(0);
for(int i = 0; i < n; i++)
sum.push_back(sum[i] + nums[i]);
}
int sumRange(int i, int j) {
return sum[j + 1] - sum[i];
}
};