12.Range Sum Query - Immutable

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

 

Note:

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

这是一个比较简单的元素相加题目。给定一个函数,输入元素的位置参数,然后得出这个区间中的元素结果。

具体代码如下:

class NumArray {
public:
  NumArray(vector<int> nums) {
    accu.push_back(0);
    for(int num : nums)
      accu.push_back(accu.back()+num);
  }

  int sumRange(int i, int j) {
    return accu[j + 1]-accu[i];
  }
private:
  vector<int> accu;
};

/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/

posted @ 2017-06-26 15:40  legooooo  阅读(142)  评论(0编辑  收藏  举报