[LeetCode]Range Sum Query - Immutable

题目描述:

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

Example:

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

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

Note:

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

题目大意:

给定整数数组nums,计算下标i与j之间的元素和(i ≤ j),包含边界。

测试样例见题目描述。

注意:

  1. 你可以假设数组不会改变。
  2. sumRange函数会调用多次。

解题思路:

计算辅助数组sums:

sums[0] = 0

sums[i+1] = sums[i] + nums[i]

则sumRange(i, j) = sums[j+1] - sums[i]

Python代码:

class NumArray(object):
    def __init__(self, nums):
        """
        initialize your data structure here.
        :type nums: List[int]
        """
        size = len(nums)
        self.sums = [0] * (size + 1)
        for x in range(size):
            self.sums[x + 1] += self.sums[x] + nums[x]

    def sumRange(self, i, j):
        """
        sum of elements nums[i..j], inclusive.
        :type i: int
        :type j: int
        :rtype: int
        """
        return self.sums[j + 1] - self.sums[i]


# Your NumArray object will be instantiated and called as such:
# numArray = NumArray(nums)
# numArray.sumRange(0, 1)
# numArray.sumRange(1, 2)

 

本文链接:http://bookshadow.com/weblog/2015/11/10/leetcode-range-sum-query-immutable/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

评论
  1. Joe Joe 发布于 2015年11月10日 14:30 #

    哈哈,你好快

张贴您的评论