303. Range Sum Query

来源:互联网 发布:在淘宝上买摩托车 编辑:程序博客网 时间:2024/06/12 21:42

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

Note:

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

2. analysis

采用动态规划中的备忘录法,先把sum[0…k]保存起来,需要计算umRange(int i, int j)的时候,直接做差即可,以空间换时间的做法,算法的时间复杂度只为O(n), 也就是计算存储sum[0..n]的时间。


3. code

class NumArray {public:    NumArray(vector<int> nums) {        if(nums.size() <= 1) {            int t = (nums.size() ==0 )? 0 :nums[0];            sum.push_back(t);        } else if(nums.size() > 1) {          sum.push_back(nums[0]);          for(int i = 1; i < nums.size(); i++) {            int t = sum[i-1] + nums[i];            sum.push_back(t);          }        }      }    int sumRange(int i, int j) {        if(i == 0)            return sum[j];        else             return sum[j] - sum[i-1];               }  private:    vector<int> sum;};/** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(i,j); */