303. Range Sum Query - Immutable

来源:互联网 发布:淘宝水弹枪合法吗 编辑:程序博客网 时间:2024/05/22 18:56

1.Question

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) -> 1sumRange(2, 5) -> -1sumRange(0, 5) -> -3

Note:

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

class NumArray {private:    vector<int> dp;public:    NumArray(vector<int> &nums) {        dp = nums;        for(int i = 1, size = nums.size(); i < size; i++)            dp[i] += dp[i-1]; //实际上也是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);

3.Note

a. 这个题里我们要注意,sumRange() 会多次调用,如果直接遍历求和会超时。那么,我们用动态规划,用数组dp 记录0~i的和,表示为dp[i]。这样如果i == 0则sumRange(i, j)返回dp[j]即可, i != 0时, i~j 的和可以用dp[j] - dp[i-1]表示。

b. dp是个vector,初始化分配空间很重要。否则会出现RE.

0 0
原创粉丝点击