题目描述
Given an integer array nums, handle multiple queries of the following type:
Calculate the sum of the elements of nums between indices left and right inclusive where left <= right. Implement the NumArray class:
NumArray(int[] nums) Initializes the object with the integer array nums. int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + … + nums[right]).
Example1:
Input [“NumArray”, “sumRange”, “sumRange”, “sumRange”] [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] Output [null, 1, -1, -3]
Explanation NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3
Constraints:
- 1 <= nums.length <= 10^4
- 10^5 <= nums[i] <= 10^5
- 0 <= left <= right < nums.length
- At most 104 calls will be made to sumRange.
解题思路
- 实现一个累加操作,类似于直方图思想
- 最后得到[left]到[right]的时候,直接由right-left
##
class NumArray {
public:
NumArray(vector<int>& nums) {
dp = nums;
for(int i = 1; i < nums.size(); i++){
dp[i] += dp[i - 1];
}
}
int sumRange(int left, int right) {
if(left == 0){
return dp[right];
}
return dp[right] - dp[left - 1];
}
private:
vector<int> dp;
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(left,right);
*/
普通解法(这个也能通过)
class NumArray {
public:
NumArray(vector<int>& nums) {
this -> nums = nums;
}
int sumRange(int left, int right) {
int res = 0;
for(int i = left; i <= right; i++){
res += nums[i];
}
return res;
}
private:
vector<int> nums;
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray* obj = new NumArray(nums);
* int param_1 = obj->sumRange(left,right);
*/