303. Range Sum Query

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]





原文地址:https://www.cnblogs.com/xiejunzhao/p/7266230.html