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

leetcode之Range Sum Query - Immutab

2016-04-06 13:38 288 查看
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.

该题目的主要思想是:因为会多次调用数值计算,所以如果每次进行暴力计算的话,会浪费大量的时间,所以选择先计算出前n项的和,在求两下标直接的和时,只需要直接进行减法运算即可。在程序运行时,应该注意i==0的情况,这个地方容易造成超出内存的错误,所以我加了一个判定条件。

class NumArray {
public:
vector<int> sum;
NumArray(vector<int> &nums) {
//计算从begin~end每个位置和
if (nums.empty())
return;
else{

sum.push_back(nums[0]);
for (vector<int>::size_type index = 1; index != nums.size(); ++index){
sum.push_back(nums[index] + sum[index - 1]);
}
}

}

int sumRange(int i, int j) {
if (i == 0){
//cout << sum[j];
return sum[j];
}
else
{
//cout << sum[j] - sum[i - 1] << endl;
return(sum[j] - sum[i-1]);
}

}
};

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