week16-leetcode #303-RangeSumQueryImmutable
链接:https://leetcode.com/problems/range-sum-query-immutable/description/
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.
Solution
class NumArray {
public:
NumArray(vector<int> nums) {
this->nums = nums;
}
int sumRange(int i, int j) {
int count = 0;
for (int index = i; index <= j; index++)
count += this->nums[index];
return count;
}
private:
vector<int> nums;
};
思路:这个题相对比较简单,给出一个数组和前后两个索引,直接就可以计算出题目所需要的子数组和了。