Solution of Range Sum Query - Immutable

本文探讨了在给定整数数组的情况下,如何高效地计算任意两个索引之间的元素之和。通过预计算前缀和数组,将查询时间从O(n)降低到O(1),整体算法的时间复杂度为O(n+k),空间复杂度为O(n)。

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

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.

Ideas of solving problems

Subtract the sum array.Calculate the sum of the previous I Numbers in advance, that is, a[I] is equal to the sum of the interval [1, I], and the consumption time is O(n).The sum of the interval [I,j] is: sum(I,j) = a[j] -a [I -1], the elapsed time of each query is O(1), and the time complexity of k queries is O(k).So in general, it’s O(n+k). The space complexity is O(n). The time consumption is 8.4Mb.

Code

type NumArray struct {
    presum []int    // 存储 [0,i] 的和
}


func Constructor(nums []int) NumArray {
    a := NumArray{}
    a.presum = append(a.presum, 0)  // 初始化 presum 数组
    for i:=1; i<=len(nums); i++ {
        t := a.presum[i-1] + nums[i-1]
        a.presum = append(a.presum, t)
    }
    return a
}


func (this *NumArray) SumRange(i int, j int) int {
    return this.presum[j+1] - this.presum[i]
}



/**
 * Your NumArray object will be instantiated and called as such:
 * obj := Constructor(nums);
 * param_1 := obj.SumRange(i,j);
 */

链接:https://leetcode-cn.com/problems/range-sum-query-immutable/solution/48mssan-chong-fang-fa-de-go-shi-xian-by-elliotxx/
来源:力扣(LeetCode)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值