# 303. Range Sum Query - Immutable

**<font color=red>难度: Easy</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/range-sum-query-immutable/

> 内容描述

```
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.
```

## 解题方案

> 思路 1
******- 时间复杂度: O(lgN)******- 空间复杂度: O(N)******

Segment Tree

beats 36.36%

```python
class NumArray:

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.n = len(nums)
        self.tree = [0] * (2 * self.n)

        def buildTree(nums):
            self.tree[self.n:] = nums[:]
            for i in range(self.n - 1, 0, -1):
                self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]

        buildTree(nums)
        

    def sumRange(self, i, j):
        """
        :type i: int
        :type j: int
        :rtype: int
        """
        i, j = i + self.n, j + self.n
        sums = 0
        while i <= j:
            if i % 2 == 1:  # 左边多出一个不能成对的
                sums += self.tree[i]
                i += 1
            if j % 2 == 0:  # 右边多出一个不能成对的
                sums += self.tree[j]
                j -= 1
            i //= 2
            j //= 2
        return sums
```





> 思路 2
******- 时间复杂度: O(1)******- 空间复杂度: O(N)******

前缀和数组

beats 89.39%

```python
class NumArray(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.pref = [num for num in nums]
        for i in range(1, len(nums)):
            self.pref[i] += self.pref[i-1]
        

    def sumRange(self, i, j):
        """
        :type i: int
        :type j: int
        :rtype: int
        """
        if i == 0:
            return self.pref[j]
        return self.pref[j] - self.pref[i-1]
```

