lintcode练习 - 943. Range Sum Query - Immutable

版权声明:原创部分都是自己总结的,如果转载请指明出处。觉得有帮助的老铁,请双击666! https://blog.csdn.net/qq_36387683/article/details/81869068

943. Range Sum Query - Immutable

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

样例

Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

注意事项

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.

解题思路:

因为会多次计算,所以我们提前把和都计算好,这样只用遍历一次数组。需要的时候直接用两个和相减就得到区间数字的和。


class NumArray(object):

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

        

    def sumRange(self, i, j):
        """
        :type i: int
        :type j: int
        :rtype: int
        """
        if i == 0:
            return self.dp[j]
        else:
            return self.dp[j] - self.dp[i-1]


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

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/81869068