[leetcode: Python]303. Range Sum Query

来源:互联网 发布:手机直播间源码 编辑:程序博客网 时间:2024/06/05 11:23

题目:
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.

题意:
求子序列的和。
要求数组不可改变,对这个函数的调用很频繁,所以尽量优化时间复杂度。

方法一:性能69ms

class NumArray(object):    def __init__(self, nums):        """        :type nums: List[int]        """        self.add = [0]        for i in nums:            self.add.append(self.add[-1] + i)    def sumRange(self, i, j):        """        :type i: int        :type j: int        :rtype: int        """        return self.add[j+1] - self.add[i]# Your NumArray object will be instantiated and called as such:# obj = NumArray(nums)# param_1 = obj.sumRange(i,j)
0 0
原创粉丝点击