Problem Description:
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
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
题目大意:
给定一个数组,多次查询从i到j的和,实现它。
Solutions:
利用一个数组存储从头到I的总和。那么i-j的和用从头到j和减去从头到i-1的和,即为所求。
Code in C++:
class NumArray {
public:
vector<int> dp;
NumArray(vector<int> &nums) {
dp.resize(nums.size());
if(!nums.empty()){
dp[0]=nums[0];
for(int i=1;i<nums.size();i++)
dp[i]=dp[i-1]+nums[i];
}
}
int sumRange(int i, int j) {
return i==0?dp[j]:dp[j]-dp[i-1];
}
};
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
近期评论