943. Range Sum Query - Immutable

题解

  一开始我用dp[i][j]来存i到j的和,然后直接返回dp[i][j]即可,时间复杂度n*n,但提交爆内存了,那就是说可以一维数组解决咯,于是想到用dp[i]代表前i个数字的和,找i j之间就是dp[j] - dp[i-1]这里要注意是i-1,否则会多减掉一个数字,这样就出答案

class NumArray(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        book = [0] * len(nums)
        book[0]= nums[0]
        for i in range(1, len(nums)):
            book[i] = book[i-1]+nums[i]
        book.append(0)
        self.book = book

    def sumRange(self, i, j):
        """
        :type i: int
        :type j: int
        :rtype: int
        """
        #print self.book,self.book[j] , self.book[i]
        
        return self.book[j] - self.book[i-1]

 

posted on 2018-03-27 17:59  usp10  阅读(104)  评论(0编辑  收藏  举报

导航