码迷,mamicode.com
首页 > 编程语言 > 详细

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

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

标签:div   print   amp   list   else   lin   mon   padding   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]





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

标签:div   print   amp   list   else   lin   mon   padding   query   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!