10/11/2020

[LeetCode] 303. Range Sum Query - Immutable

 Problem : https://leetcode.com/problems/range-sum-query-immutable/

Let  Sums[i] = nums[0] + nums[1] + ...  nums[i - 1],

then SumRange(i, j) = Sums[j+1] - Sums[i]


class NumArray:

    def __init__(self, nums: List[int]):
        self.sums = [0] * (len(nums) + 1)
        
        for i in range(len(nums)):
            self.sums[i+1] = self.sums[i] + nums[i]
        
    def sumRange(self, i: int, j: int) -> int:
        return self.sums[j+1] - self.sums[i]
        


# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)

No comments:

Post a Comment