1. 程式人生 > >303. Range Sum Query - Immutable 數組範圍求和 - 不變

303. Range Sum Query - Immutable 數組範圍求和 - 不變

family elements ger mon integer ack man gin 不變

Given an integer array nums, find the sum of the elements between indices i and j (ij), 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 數組範圍求和 - 不變