您的位置:首页 > 产品设计 > UI/UE

【leetcode题解】[E][52]303. Range Sum Query - Immutable

2015-12-23 21:41 489 查看
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:

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

Subscribe to see which companies asked this question

就是实现数据结构的动态规划。分别用left和right保存从左、从右算起的和,然后用总和减去左右就是中间的

class NumArray(object):
def __init__(self, nums):
if nums == []:
return
self.nums = nums
self.total = sum(nums)

self.left = [0]*len(nums)
self.right = [0]*len(nums)

#self.left[0] = nums[0]
for i in xrange(1,len(nums)):
self.left[i] = self.left[i-1] + nums[i-1]
#print i,self.left[i]

for i in xrange(len(nums)-2,-1,-1):
self.right[i] = self.right[i+1] + nums[i+1]
#print i,self.right[i]

"""
initialize your data structure here.
:type nums: List[int]
"""

def sumRange(self, i, j):
#print self.left
#print 'right',self.right
return self.total - self.left[i] - self.right[j]
"""
sum of elements nums[i..j], inclusive.
:type i: int
:type j: int
:rtype: int
"""

# Your NumArray object will be instantiated and called as such:
# numArray = NumArray(nums)
# numArray.sumRange(0, 1)
# numArray.sumRange(1, 2)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: