Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3
Note:
- You may assume that the array does not change.
- There are many calls to sumRange function.
求区域和,而且这个和也有可能被多次的调用,所以不能使用直接计算的方法,用dp解决,注意0这个点的特殊情况就可以了 ,代码如下:
1 class NumArray { 2 public: 3 NumArray(vector<int> &nums) { 4 sum.resize(nums.size()); 5 for(int i = 0; i < nums.size(); ++i){ 6 sum[i] = i == 0 ? nums[0] : nums[i] + sum[i - 1]; 7 } 8 } 9 10 int sumRange(int i, int j) { 11 if(i == 0) 12 return sum[j]; 13 return sum[j] - sum[i - 1]; 14 } 15 private: 16 vector<int> sum; 17 };