leetcode 303. Range Sum Query - Immutable ( Python )

652 阅读21分钟

描述

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:

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

解析

根据题意,设置一个 sums 数组,长度为 len(nums)+1 ,索引 n 对应的值即为前 n 个数字之和,最后根据 i 和 j ,利用 sums 数组,sums[j+1]-sums[i] 即可得出结果,时间复杂度为 O(1),空间复杂度为 O(N)。

解答

class NumArray(object):
def __init__(self, nums):
    """
    :type nums: List[int]
    """
    self.sums = [0]*(len(nums)+1)
    for i in range(len(nums)):
        self.sums[i+1] = self.sums[i] + nums[i] 
    print(self.sums)
def sumRange(self, i, j):
    """
    :type i: int
    :type j: int
    :rtype: int
    """
    return self.sums[j+1]-self.sums[i]
  
		

运行结果

Runtime: 60 ms, faster than 96.35% of Python online submissions for Counting Bits.
Memory Usage: 15.7 MB, less than 16.54% of Python online submissions for Counting Bits.

每日格言:常常是最终一把钥匙打开了门。

请作者吃包子 支付宝

支付宝

微信

微信