Range Sum Query - Immutable

本文介绍了解决LeetCode第303题的两种方法:一种是在每次查询时计算区间和,适用于少量查询;另一种是在初始化时预处理累积和数组,将多次查询的时间复杂度降低到常数级别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

leetcode第303题,实现一个由下标求和的程序。

这个问题看上去很简单,但是关键是怎么优化,如果直接写也可以ac,但是时间效率上回很低。

class NumArray(object):
    def __init__(self, nums):
        """
        initialize your data structure here.
        :type nums: List[int]
        """
        self.nums = nums
        

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


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

另一种办法是,在构建类的时候,实现做下处理,由于题目中要求会多次调用加和函数,因此时间应该主要浪费在这里了,可以事先做好一个加和的数组,这样可以把复杂度降到常数级,这个思路和opencv中的haar级联分类器的优化方法积分图很相似,都是运用了建表实现的。


class NumArray(object):
    def __init__(self, nums):
        """
        initialize your data structure here.
        :type nums: List[int]
        """
        self.nums = list(nums)
        for i in range(1,len(nums)):
            nums[i] += nums[i-1]
        self.numsSum = nums
        

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值