A very short Python solution


  • 17
    C
    class NumArray(object):
        def __init__(self, nums):
            self.dp = nums
            for i in xrange(1, len(nums)):
                self.dp[i] += self.dp[i-1]
    
        def sumRange(self, i, j):
            return self.dp[j] - (self.dp[i-1] if i > 0 else 0)

  • 0
    T

    Good code! Here's my slightly different execution.

    class NumArray(object):
        def __init__(self, nums):
            self.nums = nums + [0]
            for i in xrange(len(self.nums)-2, -1, -1):
                self.nums[i] += self.nums[i+1]
    
        def sumRange(self, i, j):
            return self.nums[i] - self.nums[j+1]

  • 0
    X

    @chris.zhang.336 I think if you dont' use "self.dp=nums[:]", you will change the nums.


Log in to reply
 

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