LeetCode/solutions/303. Range Sum Query - Immutable.md
2019-09-13 23:08:41 +08:00

25 lines
671 B
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [303. Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable/description/)
# 思路
用一个数组sums记录和sums[i]代表nums[0]到nums[i]的和那么sumRange(i, j)就应该等于sum[i] - sum[i-1], 注意单独判断i得0时。
注意这种面向对象的代码风格。
# C++
```C++
class NumArray {
private:
vector<int> sums;
public:
NumArray(vector<int> nums) {
int tmp = 0;
for(int num: nums) {
tmp += num;
sums.push_back(tmp);
}
}
int sumRange(int i, int j) {
if(i == 0) return sums[j];
else return sums[j] - sums[i - 1];
}
};
```