【leetcode❤python】 303. Range Sum Query - Immutable
#-*- coding: UTF-8 -*-
#Tags:dynamic programming,sumRange(i,j)=sum(j)-sum(i-1)
class NumArray(object):
sums=[]
def __init__(self, nums):
"""
initialize your data structure here.
:type nums: List[int]
"""
self.nums=nums
self.sums=nums
for i in xrange(1,len(self.sums)):
self.sums[i]+=self.sums[i-1]
def sumRange(self, i, j):
"""
sum of elements nums[i..j], inclusive.
:type i: int
:type j: int
:rtype: int
"""
if i>j or j>=len(self.sums):return 0
return self.sums[j] if i==0 else (self.sums[j]-self.sums[i-1])
numArray = NumArray([-2, 0, 3, -5, 2, -1])
print numArray.sumRange(3,4)