303. Range Sum Query - Immutable(动态规划)

时间:2021-07-10 12:22:12
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example:

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

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3 法一:暴力
 class NumArray {

 public:
vector<int> Nums; NumArray(vector<int> nums) {
Nums =nums;
} int sumRange(int i, int j) {
int res = ;
for(int k = i;k<=j;k++)
res+=Nums[k];
return res;
}
};

法二:

sumRange(i,j)=sum[j+1]−sum[i]

 class NumArray {

 public:
vector<int> Nums;
vector<int> Sums; NumArray(vector<int> nums) {
Nums =nums;
Sums = vector<int>(nums.size()+,);
for(int i = ;i<nums.size();i++)
Sums[i+]=Sums[i]+nums[i];
} int sumRange(int i, int j) {
int res = ;
res = Sums[j+]-Sums[i];
return res;
}
};