首页 > 代码库 > 303. Range Sum Query - Immutable 数组范围求和 - 不变

303. 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:

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

  1. class NumArray(object):
  2. summations = []
  3. def __init__(self, nums):
  4. """
  5. :type nums: List[int]
  6. """
  7. self.summations = []
  8. curSum = 0
  9. for i in nums:
  10. curSum = curSum + i
  11. self.summations.append(curSum)
  12. def sumRange(self, i, j):
  13. """
  14. :type i: int
  15. :type j: int
  16. :rtype: int
  17. """
  18. if i is 0:
  19. return self.summations[j]
  20. else:
  21. return self.summations[j] - self.summations[i-1]



来自为知笔记(Wiz)


303. Range Sum Query - Immutable 数组范围求和 - 不变