## 题目描述：

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:

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

## 题目大意：

1. 你可以假设数组不会改变。
2. sumRange函数会调用多次。

## 解题思路：

```sums[0] = 0

sums[i+1] = sums[i] + nums[i]
```

## Python代码：

``````class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
size = len(nums)
self.sums = [0] * (size + 1)
for x in range(size):
self.sums[x + 1] += self.sums[x] + nums[x]

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

# Your NumArray object will be instantiated and called as such:
# numArray = NumArray(nums)
# numArray.sumRange(0, 1)
# numArray.sumRange(1, 2)
``````

Pingbacks已关闭。

1. Joe 发布于 2015年11月10日 14:30 #

哈哈，你好快