(leetcode题解)Range Sum Query - Immutable

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:

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

题意是给定一个数组返回给定位置之间的元素的和。

这道题如果只求单独一个是很简单的,直接算就好,但是题目要求可能存在多个同时调用,这个我们就要考虑将每一次的结果保留下来了,这是自然想到dp。

累计到[0,i]所有位的和用sum[i+1]表示,要求就是sum[j+1]-sum[i]。C++实现如下:

class NumArray {
public:
    NumArray(vector<int> nums) {
        sum.push_back(0);
        for(int i=0;i<nums.size();i++)
            sum.push_back(sum[i]+nums[i]);
    }
    
    int sumRange(int i, int j) {
        if(i==0)
            return sum[j+1];
        return sum[j+1]-sum[i];
    }
private:
    vector<int> sum;
};

 

posted on 2017-06-16 21:14  kiplove  阅读(186)  评论(0编辑  收藏  举报

导航