1.这道题目与pat中的1046. Shortest Distance (20)相类似;
2.使用一个数组dp[i],记录0到第i个数的和
3.求i到j之间的和时,输出dp[j]-dp[i]+num[i]即可。
AC代码如下:
class NumArray {
public:
vector<int> dp;
vector<int> num;
NumArray(vector<int> &nums) {
int n=nums.size();
dp=vector<int>(n,0);
num=nums;
for(int i=0;i<n;i++)
{
if(i>0)
dp[i]=dp[i-1]+nums[i];
else
dp[0]=nums[0];
}
}
int sumRange(int i, int j) {
return dp[j]-dp[i]+num[i];
}
};
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);