您的位置:首页 > 产品设计 > UI/UE

[leetcode 303] Range Sum Query - Immutable

2015-12-08 22:29 441 查看
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) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3


Note:

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

分析:

直接创建一个vector<int>成员变量,变量长度与NUMS变量长度+1相等

vector<int>成员变量中第i个元素表示在nums中第i个元素以前的数据和;

所以sumRange(i,j)= vector<int> [j+1] - vector<int>[i];

代码:

<span style="font-size:14px;">class NumArray {
private:
vector<int> sumArray= {0};
public:
NumArray(vector<int> &nums) {
int summ = 0;
for (int n : nums) {
summ += n;
sumArray.push_back(summ);
}
}

int sumRange(int i, int j) {
return sumArray[j+1] - sumArray[i];
}
};

// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: