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

175 篇文章 0 订阅
157 篇文章 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.


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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值