# [LeetCode] 303. Range Sum Query - Immutable 区域和检索 - 不可变

2021年09月15日 阅读数：1

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.html

Example:java

```Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3```

Note:python

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

Java:this

```class NumArray {
int[] nums;

public NumArray(int[] nums) {
for(int i = 1; i < nums.length; i++)
nums[i] += nums[i - 1];

this.nums = nums;
}

public int sumRange(int i, int j) {
if(i == 0)
return nums[j];

return nums[j] - nums[i - 1];
}
}　　```

Python:url

```class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.accu = [0]
for num in nums:
self.accu += self.accu[-1] + num,

def sumRange(self, i, j):
"""
sum of elements nums[i..j], inclusive.
:type i: int
:type j: int
:rtype: int
"""
return self.accu[j + 1] - self.accu[i]　```

Python:htm

```# Time:  ctor:   O(n),
#        lookup: O(1)
# Space: O(n)
class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.accu = [0]
for num in nums:
self.accu.append(self.accu[-1] + num),

def sumRange(self, i, j):
"""
sum of elements nums[i..j], inclusive.
:type i: int
:type j: int
:rtype: int
"""
return self.accu[j + 1] - self.accu[i]　```

Python: woblog

```class NumArray(object):

def __init__(self, nums):
"""
:type nums: List[int]
"""
s, n = 0, len(nums)
self.dp = [0] * (n + 1)
for i in xrange(n):
s += nums[i]
self.dp[i + 1] = s

def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
return self.dp[j + 1] - self.dp[i]　　```

C++:

```class NumArray {
public:
NumArray(vector<int> &nums) {
accu.push_back(0);
for (int num : nums)
accu.push_back(accu.back() + num);
}

int sumRange(int i, int j) {
return accu[j + 1] - accu[i];
}
private:
vector<int> accu;
};　　```

C++:

```class NumArray {
public:
NumArray(vector<int> &nums) {
dp.resize(nums.size() + 1, 0);
for (int i = 1; i <= nums.size(); ++i) {
dp[i] = dp[i - 1] + nums[i - 1];
}
}
int sumRange(int i, int j) {
return dp[j + 1] - dp[i];
}

private:
vector<int> dp;
};
```

C++:

```class NumArray {
public:
NumArray(vector<int> &nums) {
dp = nums;
for (int i = 1; i < nums.size(); ++i) {
dp[i] += dp[i - 1];
}
}
int sumRange(int i, int j) {
return i == 0? dp[j] : dp[j] - dp[i - 1];
}
private:
vector<int> dp;
};
```

[LeetCode] 304. Range Sum Query 2D - Immutable 二维区域和检索 - 不可变

Range Sum Query - Mutable

Range Sum Query 2D - Mutable