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

来源:互联网 发布:天子星软件 编辑:程序博客网 时间:2024/06/02 02:16

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) -> 1sumRange(2, 5) -> -1sumRange(0, 5) -> -3

Note:

  1. You may assume that the array does not change.
  2. 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)


0 0
原创粉丝点击