Leetcode 303. Range Sum Query -
2019-02-18 本文已影响2人
SnailTyan
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Range Sum Query - Immutable2. Solution
- Version 1
class NumArray {
public:
NumArray(vector<int> nums) {
this->nums = nums;
}
int sumRange(int i, int j) {
int sum = 0;
for(int index = i; index <= j; index++) {
sum += nums[index];
}
return sum;
}
private:
vector<int> nums;
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/
- Version 2
class NumArray {
public:
NumArray(vector<int> nums) {
int sum = 0;
for(int num: nums) {
sum += num;
sums.push_back(sum);
}
}
int sumRange(int i, int j) {
if(i > 0) {
return sums[j] - sums[i - 1];
}
return sums[j];
}
private:
vector<int> sums;
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/![Screen Shot 2019-02-18 at 17.21.44.png](https://img.haomeiwen.com/i3232548/929965674bc9107d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)