Simple & Fast Python Solution -- Compute Cumulative Sum


  • 0
    W
    class NumArray(object):
    
        def __init__(self, nums):
            """
            :type nums: List[int]
            """
            self.cSum = [] # compute the cumulative sum of the array till current index 
            if len(nums) == 0:
                pass
            else:
                self.cSum.append(nums[0])
            if len(nums) > 1:
                for num in nums[1:]:
                    temp = self.cSum[-1] + num
                    self.cSum.append(temp)
    
        def sumRange(self, i, j):
            """
            :type i: int
            :type j: int
            :rtype: int
            """
            if i == 0:
                return self.cSum[j]
            else:
                return self.cSum[j] - self.cSum[i-1]
    
    # Your NumArray object will be instantiated and called as such:
    # obj = NumArray(nums)
    # param_1 = obj.sumRange(i,j)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.