首页 > 编程语言 > 详细

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

时间:2017-07-31 23:23:46      阅读:387      评论:0      收藏:0      [点我收藏+]

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]





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

原文:http://www.cnblogs.com/xiejunzhao/p/7266230.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!