303 Range Sum Query – Immutable(easy)

1.这道题目与pat中的1046. Shortest Distance (20)相类似;
2.使用一个数组dp[i],记录0到第i个数的和
3.求i到j之间的和时,输出dp[j]-dp[i]+num[i]即可。

Given an integer array nums, find the sum of the elements between indices i and j (ij), inclusive.

Example:

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

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

Note:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.

Subscribe to see which companies asked this question

AC代码如下:

[c language=”++”]
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);
[/c]

Leave a Reply

Your email address will not be published. Required fields are marked *