[LeetCode] Range Sum Query - Immutable

本文介绍了一种高效的区间求和方法,通过预处理数组累积和实现快速查询。该方法适用于固定数组,通过构建累积和数组accu,在初始化阶段完成所有可能区间的求和预计算。使用时只需简单计算accu[j+1]-accu[i]即可得到指定区间[i,j]的和,大幅提高了查询效率。

The idea is fairly straightforward: create an array accu that stores the accumulated sum fornums such that accu[i] = nums[0] + ... + nums[i] in the initializer of NumArray. Then just return accu[j + 1] - accu[i] in sumRange. You may try the example in the problem statement to convince yourself of this idea.

The code is as follows.


C++

 1 class NumArray {
 2 public:
 3     NumArray(vector<int> &nums) {
 4         accu.push_back(0);
 5         for (int num : nums)
 6             accu.push_back(accu.back() + num);
 7     }
 8 
 9     int sumRange(int i, int j) {
10         return accu[j + 1] - accu[i];
11     }
12 private:
13     vector<int> accu;
14 };
15 
16 
17 // Your NumArray object will be instantiated and called as such:
18 // NumArray numArray(nums);
19 // numArray.sumRange(0, 1);
20 // numArray.sumRange(1, 2); 

Python

class NumArray(object):
    def __init__(self, nums):
        """
        initialize your data structure here.
        :type nums: List[int]
        """
        self.accu = [0]
        for num in nums:
            self.accu += self.accu[-1] + num,

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


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

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4952704.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值