Blog Archive

Tuesday, December 15, 2015

[LeetCode python] 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)
'via Blog this'

No comments:

Post a Comment